저장을 습관화

NestJS - hot reload 본문

공부/node.js

NestJS - hot reload

ctrs 2023. 11. 4. 00:42

express에서 쓰던 nodemon과 같이 

어플리케이션 실행 중 파일의 변동 사항이 발생하면

자동으로 어플리케이션을 재실행시켜주는 패키지

 

[공식문서]

https://docs.nestjs.com/recipes/hot-reload

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

[적용법]

공식문서 그대로 따라가면 된다. 간단하다.

 

1. 패키지 설치

$ npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack

 

 

2. 프로젝트 root 디렉토리에 파일 생성

파일명은 'webpack-hmr.config.js'

const nodeExternals = require('webpack-node-externals');
const { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');

module.exports = function (options, webpack) {
  return {
    ...options,
    entry: ['webpack/hot/poll?100', options.entry],
    externals: [
      nodeExternals({
        allowlist: ['webpack/hot/poll?100'],
      }),
    ],
    plugins: [
      ...options.plugins,
      new webpack.HotModuleReplacementPlugin(),
      new webpack.WatchIgnorePlugin({
        paths: [/\.js$/, /\.d\.ts$/],
      }),
      new RunScriptWebpackPlugin({
        name: options.output.filename,
        autoRestart: false,
      }),
    ],
  };
};

 

 

3. main.ts에서 활성화

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
declare const module: any; /* 이 내용 추가 */

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const port = process.env.PORT || 3000;
  await app.listen(port);
  console.log(`listening on port ${port}`);

  /* 아래 내용 추가 */
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}
bootstrap();

 

 

4. package.json 수정

...
    "start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch",
    "start:dev-backup": "nest start --watch",
...

'start:dev'를 복사하여 내용을 수정하고,

기존 'start:dev'는 'start:dev-backup'으로 변경

 

 

5. 실행

$ npm run start:dev

> a-nest@0.0.1 start:dev
> nest build --webpack --webpackPath webpack-hmr.config.js --watch


 Info  Webpack is building your sources...

webpack 5.89.0 compiled successfully in 4115 ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:16     LOG [NestFactory] Starting Nest application...
[Nest] 32864  - 2023. 11. 04. 오전 12:39:16     LOG [InstanceLoader] AppModule dependencies initialized +9ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:16     LOG [RoutesResolver] AppController {/}: +25ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:16     LOG [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:16     LOG [NestApplication] Nest application successfully started +3ms
listening on port 3000

 

 

이후 파일 내용 수정 후 control+s로 저장하면 어플리케이션이 자동으로 재실행된다.

 Info  Webpack is building your sources...

Entrypoint main 45 KiB = main.js 44.2 KiB 0.089a2688a3b92d3bf420.hot-update.js 876 bytes
webpack 5.89.0 compiled successfully in 125 ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:45     LOG [NestFactory] Starting Nest application... +29027ms
[HMR] Updated modules:
[HMR]  - 3
[HMR] Update applied.
[Nest] 32864  - 2023. 11. 04. 오전 12:39:45     LOG [InstanceLoader] AppModule dependencies initialized +7ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:45     LOG [RoutesResolver] AppController {/}: +1ms        
[Nest] 32864  - 2023. 11. 04. 오전 12:39:45     LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:45     LOG [NestApplication] Nest application successfully started +0ms
Listening on port 3000

 Info  Webpack is building your sources...

Entrypoint main 45 KiB = main.js 44.2 KiB 0.81ecd1437761baacd7cf.hot-update.js 876 bytes
webpack 5.89.0 compiled successfully in 77 ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:49     LOG [NestFactory] Starting Nest application... +4114ms
[HMR] Updated modules:
[HMR]  - 3
[HMR] Update applied.
[Nest] 32864  - 2023. 11. 04. 오전 12:39:49     LOG [InstanceLoader] AppModule dependencies initialized +4ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:49     LOG [RoutesResolver] AppController {/}: +1ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:49     LOG [RouterExplorer] Mapped {/, GET} route +0ms
[Nest] 32864  - 2023. 11. 04. 오전 12:39:49     LOG [NestApplication] Nest application successfully started +1ms
listening on port 3000

 

 

[추가]

.env 파일 수정에서는 어플리케이션 재시작이 되지 않았음

수동 재시작 필요한 경우가 가끔 있다고 함..