1.热更新概念
启动WebpackDevServer是整页刷新,这里讨论的是 局部块更新。原有的变化信息保留
Hot Module Replacement(HMR: 热模块替换)
2.css模块HMR
不⽀持抽离出的css 我们要使⽤style-loader, css-loader
优点:局部刷新
//启动hmr
devServer: {
contentBase: "./dist",
open: true,
hot: true,//打开热更新,则不会整页刷新
},
//配置⽂件头部引⼊webpack
const webpack = require("webpack");
//在插件配置处添加:
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "src/index.html"
}),
new webpack.HotModuleReplacementPlugin()
],
//index.js
import "./css/index.css";
var btn = document.createElement("button");
btn.innerHTML = "新增";
document.body.appendChild(btn);
btn.onclick = function () {
var div = document.createElement("div");
div.innerHTML = "item";
document.body.appendChild(div);
};
//index.css
div: nth - of - type(odd) {
background: yellow;
}
注意启动HMR后,css抽离会不⽣效,还有不⽀持contenthash,chunkhash
3.js模块HMR
devServer: {
contentBase: "./dist",
open: true,
hot: true,//打开热更新,则不会整页刷新
// hotOnly: true, //注意hotOnly设置不设置都生效
},
//需要使⽤module.hot.accept来观察模块更新 从⽽更新
案例:
//counter.js
function counter() {
var div = document.createElement("div");
div.setAttribute("id", "counter");
div.innerHTML = 1;
div.onclick = function () {
div.innerHTML = parseInt(div.innerHTML, 10) + 1;
};
document.body.appendChild(div);
}
export default counter;
//number.js
function number() {
var div = document.createElement("div");
div.setAttribute("id", "number");
div.innerHTML = 13000;
document.body.appendChild(div);
}
export default number;
//index.js
import counter from "./counter";
import number from "./number";
counter();
number();
if (module.hot) {
module.hot.accept("./b", function () {
document.body.removeChild(document.getElementById("number"));
number();
});
}
4.vue实现热更新
vue-loader