HMR
模块热替换(Hot Module Replacement 或 HMR)允许在运行时更新各种模块,而无需进行完全刷新。
HMR主要是通过以下几种方式,来显著加快开发速度:
- 保留在完全重新加载页面时丢失的应用程序状态。
- 只更新变更内容,以节省宝贵的开发时间。
- 调整样式更加快速 - 几乎相当于在浏览器调试器中更改样式。
HMR 不适用于生产环境,这意味着它应当只在开发环境使用。
一、使用 HMR
这里,我们是基于上一节的webpack-dev-server的项目结构配置进行讲解的。
要开启HMR,我们只需要更新 webpack-dev-server 的配置 和 使用 webpack 内置的 HMR 插件 即可。
若你使用了 webpack-dev-middleware 而没有使用 webpack-dev-server,请使用 webpack-hot-middleware package 包,以在你的自定义服务或应用程序上启用 HMR。
(1)开启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:{//删除了 print.js 的入口,因为它现在正被 index.js 模块使用。app: './src/index.js' //+},devtool: 'inline-source-map',devServer: {contentBase: './dist',hot: true //+},plugins: [new CleanWebpackPlugin(['dist']),new HtmlWebpackPlugin({title:'Output Management'}),new webpack.NamedModulesPlugin(), //+new webpack.HotModuleReplacementPlugin() //+],output:{filename:'[name].bundle.js',path:path.resolve(__dirname,'dist'),publicPath: '/'}
}
这里我们还添加了 NamedModulesPlugin,以便更容易查看要修补(patch)的依赖。现在HMR已经开启!
(2)运行 npm start
(3)print.js 内部发生变化时,要可以告诉 webpack 接受更新的模块。
所以要修改 index.js.
src/index.js:
import printMe from './print.js';function component() {var element = document.createElement('div');element.innerHTML = 'Hello webpack';var oButton = document.createElement('button');oButton.innerHTML = 'click me and check console!';oButton.onclick = printMe;element.appendChild(oButton);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 的输出内容,
src/print.js:
export default function printMe() {console.log('Updating print.js...');
}
此时你会在浏览器控制台看到如下的输出:
二、使用 HMR 2.0
回到上面的示例中。如果你继续点击示例页面上的按钮,你会发现控制台仍在打印这旧的 printMe 功能。
这是因为按钮的 onclick 事件仍然绑定在旧的 printMe 函数上。
为了让它与 HMR 正常工作,我们需要使用 module.hot.accept 更新绑定到新的 printMe 函数上:
src/index.js:
import printMe from './print.js';function component() {var element = document.createElement('div');element.innerHTML = 'Hello webpack';var oButton = document.createElement('button');oButton.innerHTML = 'click me and check console!';oButton.onclick = printMe;element.appendChild(oButton);return element;
}let element = component(); // 当 print.js 改变导致页面重新渲染时,重新获取渲染的元素
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(); // 重新渲染页面后,component 更新 click 事件处理document.body.appendChild(element); })
}
现在便解决了上面的问题。
3、HMR 修改样式表
借助 style-loader的帮助,CSS 的模块热替换非常简单。当更新 CSS 依赖模块时,此 loader 在后台使用 module.hot.accept 来修补 < style> 标签。
(1)安装两个 loader :
> sudo npm install --save-dev style-loader css-loader
(2)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:'Output Management'}),new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ],output:{filename:'[name].bundle.js',path:path.resolve(__dirname,'dist'),publicPath: '/'}
}
(3)在src目录下创建styles.css,并修改./src/index.js
src/styles.css:
body {background: blue;
}
src/index.js:
import printMe from './print.js';
import './styles.css';function component() {var element = document.createElement('div');element.innerHTML = 'Hello webpack';var oButton = document.createElement('button');oButton.innerHTML = 'click me and check console!';oButton.onclick = printMe;element.appendChild(oButton);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();document.body.appendChild(element); })
}
(4)修改src/styles.css,无需完全刷新,查看其变化:
src/styles.css:
body {background: red;
}
你发现页面的背景颜色自动变为红色。
其他代码和框架
还有许多其他 loader 和示例,可以使 HMR 与各种框架和库(library)平滑地进行交互:
- React Hot Loader:实时调整 react 组件。
- Vue Loader:此 loader 支持用于 vue 组件的 HMR,提供开箱即用体验。
- Elm Hot Loader:支持用于 Elm 程序语言的 HMR。
- Redux HMR:无需 loader 或插件!只需对 main store 文件进行简单的修改。
- 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.没有必要使用 loader!只需对主要的 NgModule 文件进行简单的修改,由 HMR API 完全控制。