每次我在index.js中改变一些东西时,HMR总是完全重新加载。我得到的唯一线索是它与module.hot.accept()
有关,但我是webpack的新手,阅读非常技术的文档没有帮助。
- 来自浏览器的警告
- 我的项目结构
- package.json:
{
"name": "webpack-shits",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "webpack",
"dev": "webpack serve",
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.0"
}
}
- webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "[name].[contenthash].js",
path: path.join(__dirname, "dist"),
clean: true,
},
devtool: "inline-source-map",
devServer: {
static: path.join(__dirname, "dist"),
},
module: {
rules: [
{
test: /.css/i,
use: ["style-loader", "css-loader"],
},
{
test: /.(svg|png|jpe?g|gif)$/i,
type: "asset/resource",
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: "Webpack Shits",
template: path.join(__dirname, "src/template.html"),
favicon: path.join(__dirname, "src/logo.svg"),
}),
],
};
- index.js:
import style from "./main.css";
const h1 = document.createElement("h1");
h1.innerText = "Heading";
document.body.append(h1);
您可以尝试添加以下代码:
import "./main.css";
const h1 = document.createElement("h1");
h1.innerText = "Heading1";
document.body.append(h1);
if (module.hot) {
module.hot.dispose(() => {
document.body.innerHTML = "";
});
module.hot.accept();
}
module.hot.accept()
将为自己接受更新。
HMR登录浏览器控制台:
[HMR] Updated modules:
[HMR] - ./src/index.js
[HMR] App is up to date.