模块热替换

模块热替换(或 HMR)是 webpack 提供的最有用的功能之一。它允许在运行时更新各种模块,而无需完全刷新页面。本页面侧重于**实现**,而概念页面则提供了关于其工作原理和用途的更多详细信息。

启用 HMR

此功能非常有助于提高生产力。我们所需要做的就是更新 webpack-dev-server 配置,并使用 webpack 内置的 HMR 插件。我们还将删除 print.js 的入口点,因为它现在将被 index.js 模块消费。

webpack-dev-server v4.0.0 起,模块热替换默认启用。

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
       app: './src/index.js',
-      print: './src/print.js',
    },
    devtool: 'inline-source-map',
    devServer: {
      static: './dist',
+     hot: true,
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Hot Module Replacement',
      }),
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
      clean: true,
    },
  };

你也可以为 HMR 提供手动入口点

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const webpack = require("webpack");

  module.exports = {
    entry: {
       app: './src/index.js',
-      print: './src/print.js',
+      // Runtime code for hot module replacement
+      hot: 'webpack/hot/dev-server.js',
+      // Dev server client for web socket transport, hot and live reload logic
+      client: 'webpack-dev-server/client/index.js?hot=true&live-reload=true',
    },
    devtool: 'inline-source-map',
    devServer: {
      static: './dist',
+     // Dev server client for web socket transport, hot and live reload logic
+     hot: false,
+     client: false,
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Hot Module Replacement',
      }),
+     // Plugin for hot module replacement
+     new webpack.HotModuleReplacementPlugin(),
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
      clean: true,
    },
  };

现在我们更新 index.js 文件,以便当检测到 print.js 内部发生变化时,我们通知 webpack 接受更新后的模块。

index.js

  import _ from 'lodash';
  import printMe from './print.js';

  function component() {
    const element = document.createElement('div');
    const btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    btn.innerHTML = 'Click me and check the console!';
    btn.onclick = printMe;

    element.appendChild(btn);

    return element;
  }

  document.body.appendChild(component());
+
+ if (module.hot) {
+   module.hot.accept('./print.js', function() {
+     console.log('Accepting the updated printMe module!');
+     printMe();
+   })
+ }

开始更改 print.js 中的 console.log 语句,你将在浏览器控制台中看到以下输出(暂时不用担心 button.onclick = printMe 的输出,我们稍后也会更新这部分)。

print.js

  export default function printMe() {
-   console.log('I get called from print.js!');
+   console.log('Updating print.js...');
  }

控制台

[HMR] Waiting for update signal from WDS...
main.js:4395 [WDS] Hot Module Replacement enabled.
+ 2main.js:4395 [WDS] App updated. Recompiling...
+ main.js:4395 [WDS] App hot update...
+ main.js:4330 [HMR] Checking for updates on the server...
+ main.js:10024 Accepting the updated printMe module!
+ 0.4b8ee77….hot-update.js:10 Updating print.js...
+ main.js:4330 [HMR] Updated modules:
+ main.js:4330 [HMR]  - 20

通过 Node.js API

当使用 Webpack Dev Server 结合 Node.js API 时,不要将开发服务器选项放在 webpack 配置对象上。相反,在创建时将其作为第二个参数传递。例如

new WebpackDevServer(options, compiler)

要启用 HMR,你还需要修改你的 webpack 配置对象以包含 HMR 入口点。以下是一个小示例,展示了它可能的样子

dev-server.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const webpack = require('webpack');
const webpackDevServer = require('webpack-dev-server');

const config = {
  mode: 'development',
  entry: [
    // Runtime code for hot module replacement
    'webpack/hot/dev-server.js',
    // Dev server client for web socket transport, hot and live reload logic
    'webpack-dev-server/client/index.js?hot=true&live-reload=true',
    // Your entry
    './src/index.js',
  ],
  devtool: 'inline-source-map',
  plugins: [
    // Plugin for hot module replacement
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      title: 'Hot Module Replacement',
    }),
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
};
const compiler = webpack(config);

// `hot` and `client` options are disabled because we added them manually
const server = new webpackDevServer({ hot: false, client: false }, compiler);

(async () => {
  await server.start();
  console.log('dev server is running');
})();

请参阅 webpack-dev-server Node.js API 的完整文档

注意事项

模块热替换可能很棘手。为了说明这一点,让我们回到我们的工作示例。如果你点击示例页面上的按钮,你会发现控制台正在打印旧的 printMe 函数。

发生这种情况是因为按钮的 onclick 事件处理程序仍然绑定到原始的 printMe 函数。

为了使 HMR 正常工作,我们需要使用 module.hot.accept 将该绑定更新为新的 printMe 函数。

index.js

  import _ from 'lodash';
  import printMe from './print.js';

  function component() {
    const element = document.createElement('div');
    const btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    btn.innerHTML = 'Click me and check the console!';
    btn.onclick = printMe;  // onclick event is bind to the original printMe function

    element.appendChild(btn);

    return element;
  }

- document.body.appendChild(component());
+ let element = component(); // Store the element to re-render on print.js changes
+ document.body.appendChild(element);

  if (module.hot) {
    module.hot.accept('./print.js', function() {
      console.log('Accepting the updated printMe module!');
-     printMe();
+     document.body.removeChild(element);
+     element = component(); // Re-render the "component" to update the click handler
+     document.body.appendChild(element);
    })
  }

这只是一个例子,但还有许多其他情况很容易让人困惑。幸运的是,市面上有很多 loader(其中一些在下面提到)将使模块热替换变得更加容易。

HMR 与样式表

借助 style-loader,CSS 的模块热替换实际上相当简单。当 CSS 依赖更新时,此 loader 在后台使用 module.hot.accept 来修补 <style> 标签。

首先,我们使用以下命令安装这两个 loader

npm install --save-dev style-loader css-loader

现在我们更新配置文件以使用该 loader。

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
    },
    devtool: 'inline-source-map',
    devServer: {
      static: './dist',
      hot: true,
    },
+   module: {
+     rules: [
+       {
+         test: /\.css$/,
+         use: ['style-loader', 'css-loader'],
+       },
+     ],
+   },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Hot Module Replacement',
      }),
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
      clean: true,
    },
  };

可以通过将样式表导入模块来实现热加载

项目

  webpack-demo
  | - package.json
  | - webpack.config.js
  | - /dist
    | - bundle.js
  | - /src
    | - index.js
    | - print.js
+   | - styles.css

styles.css

body {
  background: blue;
}

index.js

  import _ from 'lodash';
  import printMe from './print.js';
+ import './styles.css';

  function component() {
    const element = document.createElement('div');
    const btn = document.createElement('button');

    element.innerHTML = _.join(['Hello', 'webpack'], ' ');

    btn.innerHTML = 'Click me and check the console!';
    btn.onclick = printMe;  // onclick event is bind to the original printMe function

    element.appendChild(btn);

    return element;
  }

  let element = component();
  document.body.appendChild(element);

  if (module.hot) {
    module.hot.accept('./print.js', function() {
      console.log('Accepting the updated printMe module!');
      document.body.removeChild(element);
      element = component(); // Re-render the "component" to update the click handler
      document.body.appendChild(element);
    })
  }

body 上的样式更改为 background: red;,你应该会立即看到页面的背景颜色变化,而无需完全刷新。

styles.css

  body {
-   background: blue;
+   background: red;
  }

其他代码和框架

社区中还有许多其他 loader 和示例,可以使 HMR 与各种框架和库平稳交互...

  • React Hot Loader:实时调整 React 组件。
  • Vue Loader:此 loader 开箱即用地支持 Vue 组件的 HMR。
  • Elm Hot webpack Loader:支持 Elm 编程语言的 HMR。
  • Angular HMR:无需 loader!HMR 支持内置于 Angular CLI 中,只需向 ng serve 命令添加 --hmr 标志即可。
  • Svelte Loader:此 loader 开箱即用地支持 Svelte 组件的 HMR。

19 贡献者

jmreidyjhnnssararubinrohannairjoshsantosdrpicoxskipjacksbaidongdi2290bdwaincarylixgirmaEugeneHlushkoAnayaDesignaviyacohendhruvduttwizardofhogwartsaholznersnitin315