webpack热更新原理
1、什么是HMR
Hot Module Replacement是指当你对代码修改并保存后,webpack将会对代码进行新打爆,并将新的模块发送到浏览器端。
相对于live reload 刷新页面的方案, HMR的有点在于保存应用的状态,提高开发效率。
2、搭建HMR项目
1、需要 cnpm i webpack webpack-cli webpack-dev-server html-webpack-plugin express socket.io events -S
// package.json
{
"name": "15.hmr",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"express": "^4.17.1"
},
"dependencies": {
"express": "^4.17.1",
"html-webpack-plugin": "^4.4.1",
"mime": "^2.4.6",
"socket.io": "^2.3.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
项目结构
3、热更新流程图
3、项目文件
// webpack.config
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.join(__dirname, "dist"),
},
devServer: {
hot: true,
contentBase: path.join(__dirname, "dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html",
}),
new webpack.HotModuleReplacementPlugin()
],
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack热更新</title>
</head>
<body>
<div id="root"></div>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
// 入口文件:
// src/title.js
module.exports = 'title7';
// src/index.js // 入口文件
import '../webpackHotDevClient';
let root = document.getElementById("root");
function render() {
let title = require("./title");
root.innerHTML = title;
}
render(); // 渲染页面用
i