HMR简单介绍

563 阅读1分钟

什么是HMR

当我们对代码进行修改时,webpack对代码重新进行打包,并且将新的模块发送到浏览器端,浏览器将旧的模块用新的替换,在不完全刷新页面的情况下,对我们的应用进行局部更新。

HMR有什么优势

  • 它可以在刷新页面的情况下,对模块进行热替换,这个过程中,不会丢失应用程序状态
  • 只更新变更的内容,节约时间,提升了开发效率
  • 在代码中修改js/css时,感觉就像在 Chrome 的开发者工具中直接修改元素样式。

HMR在vue,react中的使用

vue-loaader已经实现了hmr,react在底层也有这部分逻辑,所以,在使用vue和react时,不需要额外设置

if(module.hot) {
    module.hot.accept('./hello.js', function() {
        div.innerHTML = hello()
    })
}

webpack配置hot是否需要配置HotModuleReplacementPlugin

Note that webpack.HotModuleReplacementPlugin is required to fully enable HMR. If webpack or webpack-dev-server are launched with the --hot option, this plugin will be added automatically, so you may not need to add this to your webpack.config.js. See the HMR concepts page for more information.

官方文档中说,完全开启HMR需要配置HotModuleReplacementPlugin。如果webpack或者webpack-dev-server是通过--hot这个选项启动的,那么这个plugin会自动加到webpack的配置中。

但在使用过程中发现,devServer配置为hot:true后,不需要再添加HotModuleReplacementPlugin也可以实现HMR,这是因为在webpack-dev-server源码中已经判断了这部分逻辑

 if (options.hot || options.hotOnly) {
        config.plugins = config.plugins || [];
        if (
          !config.plugins.find(
            // Check for the name rather than the constructor reference in case
            // there are multiple copies of webpack installed
            (plugin) => plugin.constructor.name === 'HotModuleReplacementPlugin'
          )
        ) {
          config.plugins.push(new webpack.HotModuleReplacementPlugin());
        }
      }

当配置了devServer.hot:true时,就自动添加这个插件。