HMR always full reload everytime I change something in index.js. The only clue I got is it has something to do with module.hot.accept()
, but I'm new to webpack and reading the very technical docs doesn't help.
Here is the details:
- The warning from browser
- My project's structure
- 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);
CodePudding user response:
You can try to add the following code:
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()
will accept updates for itself.
The HMR logs in browser console:
[HMR] Updated modules:
[HMR] - ./src/index.js
[HMR] App is up to date.