知海

热模块替换指南

webpackjsorg-main指南-教程

T> 本指南基于开发指南中的代码示例。

热模块替换(Hot Module Replacement,简称 HMR)是 webpack 提供的最有用的功能之一。它允许在运行时更新各种模块,而无需进行完整刷新。本页重点介绍实现,而概念页面则更详细地说明了其工作原理以及为什么有用。

W> HMR 不适用于生产环境,这意味着它只能在开发时使用。有关更多信息,请参阅生产环境构建指南

启用 HMR

此功能对生产力大有裨益。我们只需更新 webpack-dev-server 配置,并使用 webpack 内置的 HMR 插件。我们还将移除 print.js 的入口点,因为它现在将由 index.js 模块使用。

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

T> 如果你使用的是 webpack-dev-middleware 而不是 webpack-dev-server,请使用 webpack-hot-middleware 包在自定义服务器或应用中启用 HMR。

webpack.config.js

diff 复制代码
  import path from 'node:path';
  import { fileURLToPath } from 'node:url';
  import HtmlWebpackPlugin from 'html-webpack-plugin';

  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);

  export default {
    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

diff 复制代码
  import path from 'node:path';
  import { fileURLToPath } from 'node:url';
  import HtmlWebpackPlugin from 'html-webpack-plugin';
+ import webpack from 'webpack';

  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);

  export default {
    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,
    },
  };

T> 你可以使用 CLI 通过以下命令修改 webpack-dev-server 配置:webpack serve --hot-only

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

index.js

diff 复制代码
  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

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

console

diff 复制代码
[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

当通过 Node.js API 使用 Webpack Dev Server 时,不要将 dev server 选项放在 webpack 配置对象上。相反,在创建时将它们作为第二个参数传入。例如:

new WebpackDevServer(options, compiler)

要启用 HMR,你还需要修改 webpack 配置对象以包含 HMR 入口点。下面是一个小示例:

dev-server.js

js 复制代码
import path from "node:path";
import { fileURLToPath } from "node:url";
import HtmlWebpackPlugin from "html-webpack-plugin";
import webpack from "webpack";
import WebpackDevServer from "webpack-dev-server";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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);

try {
  await server.start();
  console.log("dev server is running");
} catch (err) {
  throw new Error(`Failed to start dev server: ${err.message}`, { cause: err });
}

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

T> 如果你正在使用 webpack-dev-middleware,请查看 webpack-hot-middleware 包以在自定义 dev server 上启用 HMR。

注意事项

热模块替换可能会有些棘手。为了说明这一点,让我们回到示例。如果你点击示例页面上的按钮,你会意识到控制台打印的是旧的 printMe 函数。

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

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

index.js

diff 复制代码
  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 的热模块替换实际上相当简单。这个 loader 在后台使用 module.hot.accept 在 CSS 依赖更新时修补 <style> 标签。

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

bash 复制代码
npm install --save-dev style-loader css-loader

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

webpack.config.js

diff 复制代码
  import path from 'node:path';
  import { fileURLToPath } from 'node:url';
  import HtmlWebpackPlugin from 'html-webpack-plugin';

  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);

  export default {
    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,
    },
  };

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

project

diff 复制代码
  webpack-demo
  ├── package.json
  ├── webpack.config.js
  ├── /dist
  │   └── bundle.js
  └── /src
      ├── index.js
      ├── print.js
+     └── styles.css

styles.css

css 复制代码
body {
  background: blue;
}

index.js

diff 复制代码
  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

diff 复制代码
  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。

T> 如果你知道任何其他有助于或增强 HMR 的 loader 或插件,请提交拉取请求以将其添加到这个列表!

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。