Search code examples
javascriptnode.jswebpackwebpack-hmr

Webpack HMR for Node.js


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.


Solution

  • You can follow this:

    1. run npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack
    2. create a 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 }),
        ],
      };
    };
    
    1. inside your 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