模块热替换(Hot Module Replacement 或 HMR)是 webpack 提供的最有用的功能之一。它允许在运行时更新各种模块,而无需进行完全刷新。启用HMR启用此功能实际上相当简单。而我们要做的,就是更新 webpack-dev-server 的配置,和使用 webpack 内置的 HMR 插件。我们还要删除掉 print.js 的入口起点,因为它现在正被 index.js 模式使用。修改webpack.config.js…const webpack = require(‘webpack’)module.exports = { entry: { app: ‘./src/index.js’ }, devtool: ‘inline-source-map’, devServer: { contentBase: ‘/dist’, hot: true }, plugins: [ new CleanWebpackPlugin([‘dist’]), new HtmlWebpackPlugin({// 使用htmwebpackplugin插件 title: ‘Output Management’ }), new webpack.NamedModulesPlugin(), // 以便更容易查看要修补(patch)的依赖。 new webpack.HotModuleReplacementPlugin() ],…};注意,我们还添加了 NamedModulesPlugin,以便更容易查看要修补(patch)的依赖。在起步阶段,我们将通过在命令行中运行 npm start 来启动并运行 dev server。现在,我们来修改 index.js 文件,以便当 print.js 内部发生变更时可以告诉 webpack 接受更新的模块。修改index.jsimport _ from ’lodash’import printMe from ‘./print.js’function component () { var ele = document.createElement(‘div’) var btn = document.createElement(‘button’) ele.innerHTML = _.join([‘hello’, ‘webpack’, ‘world’], ’ ‘) btn.innerHTML = ‘click me and check the console’ btn.onclick = printMe ele.appendChild(btn) return ele;}document.body.appendChild(component());if (module.hot) { module.hot.accept(’./print.js’, function () { console.log(‘accepting the updated printMe module!’); printMe() })}随意修改print.js浏览器中可以看到实时变化通过 Node.js APIHMR 修改样式表安装stylee-loader css-loadercnpm install –save-dev style-loader css-loader修改webpack.config.jsconst path = require(‘path’)const HtmlWebpackPlugin = require(‘html-webpack-plugin’) // 引入htmwebpackplugin插件const CleanWebpackPlugin = require(‘clean-webpack-plugin’) // 引入CleanWebpackPlugin插件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({// 使用htmwebpackplugin插件 title: ‘Output Management’ }), new webpack.NamedModulesPlugin(), // 以便更容易查看要修补(patch)的依赖。 new webpack.HotModuleReplacementPlugin() ], output: { filename: ‘[name].bundle.js’, // __dirname表示当前文件所在的目录的绝对路径 path: path.resolve(__dirname, ‘dist’), publicPath: ‘/’ }};cnpm start启动服务修改样式文件