nestjs热重载

nestjs每次都要重新编译,在腾讯云社区里面找到了添加热重载的方法,使用>webpack

第一步>安装需要的包

npm i --save-dev webpack webpack-cli webpack-node-externals

第二步

在根目录中添加webpack配置文件 > webpack.config.js
const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  entry: ['webpack/hot/poll?100', './src/main.ts'],
  watch: true,
  target: 'node',
  externals: [
    nodeExternals({
      whitelist: ['webpack/hot/poll?100'],
    }),
  ],
  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  mode: 'development',
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'server.js',
  },
};

第三步

修改nestjs启动文件> main.ts
declare const module: any;//添加项

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  await app.listen(3000);

//添加项
  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }
}
bootstrap();

第四步

在package.json里面加入script配置>

"start": "node dist/server",
"webpack": "webpack --config webpack.config.js"

最后

先运行这条命令通过webpack编译

npm run webpack

编译完成后启动

npm run start

如果编译或者启动报错的话看看是不是哪里目录层级出错了 找到相应位置文件更改试试

你可能感兴趣的:(nestjs热重载)