개발을 할 때 코드를 작성하고, 새로 작성한 코드를 적용하기 위해서는 서버를 멈추고 재시작을 반복해야 한다.
매 번 서버를 멈추고 다시 시작하는 것은 매우 번거로운 일이다.
Nest.js를 사용하기 전에는 nodemon 모듈을 주로 사용했는데, Nest.js 에서는 Hot Reload 기능을 추가해서 사용할 수 있다.
공식문서에 Nest CLI를 설치 / 미설치 상황을 나누어서 정리가 돼 있는데, 난 CLI를 설치했기 때문에 설치한 경우를 기준으로 정리했다.
먼저 아래 명령어로 필요한 패키지들을 설치한다.
npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
패키지들을 설치 한 후 프로젝트 폴더에 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 }),
],
};
};
HMR(Hot-Module-Replacement)를 활성화하기 위해 main.ts 파일에 웹팩 관련 내용을 추가한다.
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();
실행을 간단하게 하기 위해서 package.json 파일에서 스크립트를 수정해준다.
"scripts" : {
"start:dev": "nest build --webpack --webpackPath webpack-hmr.config.js --watch"
}
package.json 수정 후 실행
npm run start:dev
공식문서에 작성된 대로만 따라하면 잘 작동된다.
<참조>
https://docs.nestjs.com/recipes/hot-reload#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 Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
'Backend' 카테고리의 다른 글
[Spring Boot]GlobalExceptionHandler (Feat. @ControllerAdvice) (0) | 2024.02.21 |
---|---|
[Nest.js(Node.js)]Naver Cloud Platform 으로 문자 서비스(SMS) API 구현 (0) | 2022.03.07 |
[Nest.js]Parsing error: cannot read file tsconfig.json (0) | 2022.02.09 |
[Nest.js] TypeError: (0 , cookie_parser_1.default) is not a function (0) | 2022.02.09 |