Webpack HMR for Node.js



我使用webpack来绑定我的nodejs代码。众所周知,我们可以使用webpack-dev-server为dev构建一个环境,那么nodejs呢?我知道nodemon可以工作,但它重新启动了整个项目,我想要一种HMR的方式。

您可以按照以下步骤操作:

  1. 运行npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
  2. 在应用程序的根目录中创建一个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 }),
],
};
};
  1. main.js中:
async function bootstrap() {
<Your Express middleware and etc>
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => server.close());
}
}

灵感来自Nest.js HMR

最新更新