静态页面如何使用, webpack来实现自动更新?
1.创建npm配置文件 package.json
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
2.安装webpack
3.安装webpack-dev-server
webpack.config.js
module.exports = {
// ...
devServer: {
hot: true,
},
};
补充
补充:用 webpack + webpack-dev-server 实现静态页面的"保存即刷新 / 热更新"完整步骤:
初始化项目(在项目根目录执行):
npm init -y npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin新增入口与 HTML 模板:
src/index.js:import "./style.css"; document.body.innerText = "Hello, webpack devServer";
public/index.html:<!doctype html> <html><body><script src="main.js"></script></body></html>
webpack.config.js关键配置:const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { mode: "development", entry: "./src/index.js", output: { path: path.resolve(__dirname, "dist"), filename: "main.js" }, devServer: { static: "./dist", hot: true, open: true, port: 8080, }, plugins: [new HtmlWebpackPlugin({ template: "./public/index.html" })], };
package.json增加脚本:"scripts": { "start": "webpack serve --open" }
npm run start—— webpack-dev-server 会在http://localhost:8080起服务,修改src/index.js后浏览器会热更新(HMR)而无需手动刷新;非 JS 资源(HTML、CSS)默认整页刷新,可借助style-loader+ HMR 实现样式热替换。
来源整理自:我的有道云笔记



