I use webpack
to bundle my nodejs code. As well known, we could use webpack-dev-server
to build an environment for dev, so how about nodejs? I know nodemon
can work, but it restart the whole project, I want a HMR way.
You can follow this:
npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
webpack-hmr.config.js
file in the root directory of your application and put this:
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 }),
],
};
};
main.js
:async function bootstrap() {
<Your Express middleware and etc>
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => server.close());
}
}
inspired by Nest.js HMR