与 webpack-dev-middleware 一起使用

  1. 通过 npm 安装 webpack-dev-middleware

    npm i -D webpack-dev-middleware webpack-hot-middleware
    
  2. 修改 webpack.config.js

    • webpack-hot-middleware/client 添加到 entry 中定义的每个项目

    • new webpack.HotModuleReplacementPlugin() 添加到 plugins

      module.exports = {
          entry: {
              js: [
                  './index.js',
                  'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true'
              ]
          },
          plugins: [
              new webpack.HotModuleReplacementPlugin()
          ]
      };
      
  3. 将这些添加到 index.js

    var webpack = require('webpack');
    var webpackDevMiddleware = require('webpack-dev-middleware');
    var webpackHotMiddleware = require('webpack-hot-middleware');
    
    var config = require('./webpack.config.js');
    var compiler = webpack(config);
    
    app.use(webpackDevMiddleware(compiler, {
        noInfo: true,
        publicPath: config.output.publicPath,
        stats: { colors: true },
        watchOptions: {
            aggregateTimeout: 300,
            poll: true
        },
    }));
    
    app.use(webpackHotMiddleware(compiler, {
        log: console.log,
    }));