赞
踩
webpack官方文档(devserverhot)中介绍,使用hmr的时候,需要满足两个条件:
Note that
webpack.HotModuleReplacementPlugin
is required to fully enable HMR. Ifwebpack
orwebpack-dev-server
are launched with the--hot
option, this plugin will be added automatically, so you may not need to add this to yourwebpack.config.js
*.
请注意:webpack要完全启用HMR需要使用
webpack.HotModuleReplacementPlugin
。如果webpack或webpack-dev-server 通过命令行添加--hot
选项启动,这个插件会自动添加,所以您不需要将它添加到webpack.config.js中
但是,经实际使用 webpack-dev-server 时发现,在webpack.config.js中仅仅配置了devServer.hot:true
,而未添加这个插件的状态下,仍然实现了HMR。
原来 webpack-dev-server 内部自动帮我们完成了这个事情。
通过在Github 的 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());
}
}
代码判断了配置的插件中是否包含名为HotModuleReplacementPlugin的插件,如果没有则添加。
再查看搜索结果中的Commits:fix: check for name of HotModuleReplacementPlugin to avoid RangeError #2146
这段代码还被调整过,调整前判断的依据是constructor,调整后用name判断。
至此,我们确定,webpack-dev-sever内部对HotModuleReplacementPlugin插件做了判断,当配置了devServer.hot:true
时,就自动添加这个插件。
但是webpack源码中未搜到类似操作,所以使用其他工具启用服务器并开启HMR时,应该仍需手动添加这个插件。
PS:可能需要你自己尝试验证一下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。