webpack Hot Module Replacement Use with webpack-dev-server


Example

  1. Install webpack-dev-server via npm.

    npm i -D webpack-dev-server
    
  2. Configure webpack-dev-server by adding server.js.

    // server.js
    
    var webpack = require("webpack");
    var WebpackDevServer = require("webpack-dev-server");
    var config = require("./webpack.dev.config");
    
    var server = new WebpackDevServer(webpack(config), {
        // ...
    });
    
    server.listen(8080);
    
  3. Modify webpack.config.js

    • Add webpack-dev-server/client to each items defined in "entry".

    • Add webpack/hot/only-dev-server to each items defined in "entry".

      • NOTE: Change if needed...
      • Use webpack/hot/only-dev-server to block page refresh if HMR fails.
      • Use webpack/hot/dev-server to auto-refresh page if HMR fails.
    • Add new webpack.HotModuleReplacementPlugin() to "plugins"

      module.exports = {
          entry: {
              js: [
                  'webpack-dev-server/client?http://localhost:8080'
                  'webpack/hot/only-dev-server',
                  './index.js'
              ]
          },
          plugins: [
              new webpack.HotModuleReplacementPlugin()
          ]
      };
      
  4. Add hot: true in webpack-dev-server configuration

    var server = new WebpackDevServer(webpack(config), {
        hot: true
    
        // ... other configs
    });