NestJS启动令人难以置信的开发速度

Øys*_*sen 5 node.js typescript ts-node nestjs

我在开发环境中的应用程序在启动阶段非常缓慢。我在各个地方设置了一些调试日志,以查看花费了很多时间,并且发现我main.ts实际上花了将近9分钟的时间app.module导入我的!

资源

import { performance } from 'perf_hooks';
const startTime = performance.now();

import { Log } from 'api/common/util/logger/log';
Log.log.info(`??????????????????????????????????????????????????????????????`);
Log.log.info(`?    Starting: ${new Date().toISOString()}                      ?`);
Log.log.info(`??????????????????????????????????????????????????????????????`);

// From here -------------------->
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import 'reflect-metadata';
import { existsSync, mkdirSync, writeFile } from 'fs';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as helmet from 'helmet';
import * as morgan from 'morgan';
import * as morganBody from 'morgan-body';
// <------ to here, imports fly in as expected.

// Theese take a bit longer, but not enormously
import { Config } from './api/common/config';
import { HttpExceptionFilter } from './api/common/filters/http-exception.filter';
import { LogService } from 'api/common/util/logger/log.service';

// This one takes up the most time on startup (several minutes)
import { AppModule } from './api/app.module';
Log.log.debug(` * imports done in ${(performance.now() - startTime).toFixed(3)}ms`);
Log.log.debug(` * Memory: ${readMem()}`);

function readMem() {
  const mem = process.memoryUsage();
  const convert = { Kb: n => (n / 1024), Mb: n => convert.Kb(n) / 1024 };
  const toHuman = (n, t) => `${convert[t](n).toFixed(2)}${t}`;
  return `Used ${toHuman(mem.heapUsed, 'Mb')} of ${toHuman(mem.heapTotal, 'Mb')} - RSS: ${toHuman(mem.rss, 'Mb')}`;
}
Run Code Online (Sandbox Code Playgroud)

输出量

生产启动:

$ node dist/main.js
info: ????????????????????????????????????????????????????????????????????????????
info: ?    Starting: 2019-01-29T13:06:13.751Z                                    ?
info: ?      Memory: Used 6.54Mb of 11.70Mb - RSS: 25.33Mb                       ?
info: ?     Runtime: js                                                          ?
info: ????????????????????????????????????????????????????????????????????????????
debug:  * imports done in 6862.350ms
debug:  * Memory: Used 87.99Mb of 113.76Mb - RSS: 133.58Mb
info: Nest application successfully started
info: ????????????????????????????????????????????????????????????????????????????
info: ?             Memory: Used 93.71Mb of 122.52Mb - RSS: 144.20Mb             ?
info: ?             Launch: 2019-01-29T13:06:25.377Z                             ?
info: ?      Time to start: 11991.049ms                                          ?
info: ?     Bootstrap time: 5124.189ms                                           ?
info: ????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

开发启动:

$ ts-node -r tsconfig-paths/register src/main.ts
info: ????????????????????????????????????????????????????????????????????????????
info: ?    Starting: 2019-01-29T13:08:06.914Z                                    ?
info: ?      Memory: Used 157.76Mb of 193.62Mb - RSS: 209.77Mb                   ?
info: ?     Runtime: ts                                                          ?
info: ????????????????????????????????????????????????????????????????????????????
debug:  * imports done in 471159.063ms
debug:  * Memory: Used 297.45Mb of 385.35Mb - RSS: 408.90Mb
info: Nest application successfully started
info: ????????????????????????????????????????????????????????????????????????????
info: ?             Memory: Used 216.64Mb of 383.35Mb - RSS: 409.11Mb            ?
info: ?             Launch: 2019-01-29T13:16:05.521Z                             ?
info: ?      Time to start: 483228.325ms                                         ?
info: ?     Bootstrap time: 12042.239ms                                          ?
info: ????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

是的,我开始使用ts-node,但这是NestJS建议进行开发和调试的。

如何优化启动,以使后端的每个微小更改都不需要10分钟的拖延?我已经无法专心,这无济于事。

我的模块太多了吗?如果结合使用会有所帮助吗?我具有大约15个数据库实体模型,每个模型都包含在其自己的基于graphql的模块中,以提高可读性,但是其中许多模型具有循环依赖性,可通过forwardRef()在模块导入中注入来解决。这可能是个问题吗?

我尝试包括尽可能少的第三方库,以避免node_modules地狱。我在模块中导入的是我自己的代码或NestJS框架。当然,我不知道会加载多少隐式依赖关系,但是我随身携带的库的数量会影响启动性能吗?如果是这样,我该如何监视堆栈中包含的内容以及每个脚本在评估时消耗多少内存/ cpu?我可以以某种方式预编译其中的一部分以增加启动速度吗?

在生产环境中以编译的javascript运行时,我没有这个问题。

小智 5

尝试设置 env TS_NODE_TRANSPILE_ONLY=true

例如 TS_NODE_TRANSPILE_ONLY=true ts-node -r tsconfig-paths/register src/main.ts

文档:https : //github.com/TypeStrong/ts-node#cli-and-programmatic-options

它加快了我的应用程序启动速度


Jay*_*iel 5

一种选择是使用tsc-watch而不是 ts-node 和 nodemon。您可以在 start:dev 中设置启动命令,如下所示:

{
  //this is assuming you're building to the dist folder
  ...
  "start:dev": "tsc-watch --onSuccess \"node dist/main.js\" --onFailure \"echo 
  There was a problem with the build!\" -p tsconfig.json" 
  ...
}
Run Code Online (Sandbox Code Playgroud)

ts-node根据我的经验,我在注册路线时遇到了太多问题,而且加载时间也快要了我的命。我得到tsc-watch了项目的全新构建,仅重建已更改的文件。通过这种方式,您还可以tsc在开发时测试是否有效。


我还使用 tsconfig-bootstrap 命令导入自定义路由(在 tsconfig 中定义)并将其添加到我的启动命令中node -r path/to/my/script.js dist/main.js

希望这对您有一点帮助!