熱模組替換

熱模組替換(或 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(選項, 編譯器)

若要啟用 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);
    })
  }

這只是一個範例,但還有許多其他範例很容易讓人們絆倒。幸運的是,有許多載入器(其中一些載入器在下方提及)可以讓熱模組替換變得更容易。

HMR 搭配樣式表

style-loader 的協助下,熱模組替換搭配 CSS 其實相當直接。此載入器在幕後使用 module.hot.accept 來修補 <style> 標籤,當 CSS 相依項更新時。

首先,讓我們使用下列指令安裝兩個載入器

npm install --save-dev style-loader css-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;
  }

其他程式碼和架構

社群中有許多其他載入器和範例,可以讓 HMR 與各種架構和函式庫順利互動...

19 貢獻者

jmreidyjhnnssararubinrohannairjoshsantosdrpicoxskipjacksbaidongdi2290bdwaincarylixgirmaEugeneHlushkoAnayaDesignaviyacohendhruvduttwizardofhogwartsaholznersnitin315