关于HMR,它的介绍:
Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running without a page reload
并且它只是针对dev model :
HMR is not intended for use in production, meaning it should only be used in development. See the building for production guide for more information.
要使用它,先要在devServer对象中将其开启hot设置true:参考这里
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true, //gzip
hot: true,
port: 9000,
stats: "errors-only", //only show the error message in terminal
open: true //will open a new browser widow when the dev server for the the first sound
},
并把webpack引入到webpack.config.js中:
const webpack = require('webpack');
再在plugins对象中再加入下面两个plugin:
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
记得把ExtractTextPlugin disable掉:
new ExtractTextPlugin({
filename: "styles.css",
disable: true,
allChunks: true
})
关于为什么要disable掉,可能这里可以解释
同时也把css rule也改成不用ExtractTextPlugin的方式:
{
test: /\.scss$/,
use: ['style-loader','css-loader','sass-loader']
}
这个时候去build下(npm run dev),并update app.scss里的p的color 为其他的颜色,可以发现页面中的p的颜色会相应的改变,并且是在没有刷新页面的前提下,在控制台只看了app.scss更新了(先不管其他的error):
在dev model下,把ExtractTextPlugin给禁掉了,可是又想在prot model 下正常使用它,怎么实现呢?可以这样:
先将Script对象中的prot命令改成:
"scripts": {
"dev": "webpack-dev-server",
"prot": "npm run clean && NODE_ENV=production webpack -p",
"clean": "rimraf ./dist/*"
}
然后在webpack.config.js中这样去配置:
var isProt = process.env.NODE_ENV === 'production'; // true or false
var cssDev = ['style-loader','css-loader','sass-loader'];
var cssProt = ExtractTextPlugin.extract({
fallback:"style-loader",
use: ['css-loader','sass-loader'],
publicPath: "/dist"
})
var cssConfig = isProt ? cssProt : cssDev;
再把css rule更成这样:
{
test: /\.scss$/,
use: cssConfig
}
记得改ExtractTextPlugin里的disable属性为动态的:
new ExtractTextPlugin({
filename: "styles.css",
disable: !isProt,
allChunks: true
})
完成后,当运行dev模式的时候,会正常的启用HMR,而在prot模式下,ExtractTextPlugin也能正常使用:
梳理下:
如果使用HMR,它应该只是对于dev model才对,但是开发模式的时候,如果设置ExtractTextPlugin为enable的话,HMR将失效,所以开发模式下,应该不使用ExtractTextPlugin,不使用ExtractTextPlugin就意味着最终页面的出现的源码里没有外部的css文件会在head里,会呈现出pure CSS在head里。而对于production模式来说,又想使用ExtractTextPlugin,所以综上就可以使用上面的这种配置方式来灵活切换了。