webpack 模块热更新 Hot Module Replacement

webpack 模块热更新 Hot Module Replacement

GitHub 学习 Demo。

Hot Module Replacement (简称 HMR) 是一个由 webpack 提供的最有用的功能之一。它允许在运行时更新所有类型的模块,而不需要完全刷新。

意思就是,部分的代码更新。而不是重新编译后刷新。

这篇文章关注的是功能的实现。如果想了解热更新的实现原理,请点击链接。

warnning : 本指南中的工具仅用于开发,请避免在生产中使用它们!

启用 HMR

这个功能可以大大提升你的开发效率。在下面的例子中,将会去除 print.js 的入口,直接由 index.js 使用。

tips:
如果你是使用 webpack-dev-middleware 中间件 来搭建开发服务器的话,请添加 webpack-hot-middleware 中间件来开启 HMR。

修改项目
# webpack.config.js

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

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

然后修改 index.js,从而当 print.js 发生变化,我们告诉 webpack 去接受这个已更新的 module。

# src/index.js

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

  function component() {
    var element = document.createElement('div');
    var 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();
+   })
+ }
复制代码
运行项目
npm start
# npx webpack-dev-server --config webpack.config.js
复制代码

运行项目后,尝试修改print.jsconsole.log输出的内容, 然后你会发现,每当模块更新后,浏览器的控制台都会输出新的内容。 说明新的改动已被 webpack 加载。

[WDS] App updated. Recompiling...
client:243 [WDS] App hot update...
index.js:24 Accepting the updated printMe module!
复制代码

但是,你会发现再点击按钮还是输出原来的内容。别急,后面会让这部分也更新。

webpack-dev-server 的 Node API 用法

当你使用这种方式搭建你的开发环境的时候。不要在 webpack 的配置对象中声明 devServer 选项。而且需要显示的调用 webpack-dev-server 包下的 addDevServerEntrypoints 方法声明 webpack 的入口文件。

# server.js

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

const config = require('./webpack.config.js');
const options = {
  contentBase: './dist',
  hot: true,
  host: 'localhost'
};

webpackDevServer.addDevServerEntrypoints(config, options);
const compiler = webpack(config);
const server = new webpackDevServer(compiler, options);

server.listen(5000, 'localhost', () => {
  console.log('dev server listening on port 5000');
});
复制代码

tips:
如果你是使用 webpack-dev-middleware 中间件 来搭建开发服务器的话,请添加 webpack-hot-middleware 中间件来开启 HMR。

Gotchas

Hot Module Replacement 可能很棘手。刚的例子未解决的问题是,模块更新后,点击按钮还是输出旧的内容。

这是因为,这是 DOM 元素依旧绑定的是旧的方法。。。。

解决方法之一是,手动更新 DOM 事件绑定的方法:

# src/index.js

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

  function component() {
    var element = document.createElement('div');
    var 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);
    })
  }
复制代码

但这样显得很麻烦。后面会提到一些 loaders 可以让我们更方便的使用 HMR。

样式表的 HMR

CSS 的 Hot Module Replacement 实际上是依赖 style-loader 的帮助。当 CSS 依赖更新的时候,这个 loader 通过 module.hot.accept 在幕后更新 <style> 标签。

安装依赖
npm install --save-dev style-loader css-loader
复制代码
修改项目
  webpack-demo
  | - package.json
  | - webpack.config.js
  | - /dist
    | - bundle.js
  | - /src
    | - index.js
    | - print.js
+   | - styles.css

# src/styles.css

body {
  background: blue;
}

# index.js

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

  function component() {
    var element = document.createElement('div');
    var 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);
    })
  }

# webpack.config.js

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

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

你会发现,当你修改样式表后,浏览器中页面的样式已经变化了。

使用 loaders 便捷使用 HMR

  • React Hot Loader: Tweak react components in real time.
  • Vue Loader: This loader supports HMR for vue components out of the box.
  • Elm Hot Loader: Supports HMR for the Elm programming language.
  • Angular HMR: No loader necessary! A simple change to your main NgModule file is all that's required to have full control over the HMR APIs.

更多阅读

NEXT

后面我们将探讨如何利用 webpack 来对项目进行各种的优化。第一个讲解 Tree Shaking 摇树处理

转载于:https://juejin.im/post/5c8e7b1df265da681a02f82c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值