更新Node.js与Webpack后webpack-dev-server热重载失效求助
问题:Webpack DevServer自动重载失效,无法配置ES6支持
更新Node.js与Webpack后,DevServer无法实现自动重载,尝试过设置mode: "development"、static、hot: true等配置均无效,控制台无任何报错。仅需将Webpack配置为支持ES6编写,相关配置及环境信息如下:
package.json配置
{ "name": "calc", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --hot", "build": "webpack -d" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.19.3", "@babel/preset-env": "^7.19.3", "babel-loader": "^8.2.5", "webpack": "^5.74.0", "webpack-cli": "^4.10.0", "webpack-dev-server": "^4.11.1" } }
webpack.config.js配置
const path = require("path"); const entryPath = "."; module.exports = { mode: "development", entry: `./${entryPath}/js/app.js`, output: { filename: "out.js", path: path.resolve(__dirname, `${entryPath}/build`), }, r: { static: path.join(__dirname, `${entryPath}`), hot: true, compress: true, port: 3001, open: true, headers: { "Access-Control-Allow-Origin": "*" }, }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"], }, }, }, ], }, };
目录结构

环境版本
- Node.js:v18.9.0
- NPM:8.19.1
解决方案
1. 修正DevServer配置拼写错误
webpack.config.js中把r: {改为devServer: {——这是导致DevServer配置完全不生效的核心原因。
2. 优化启动命令
Webpack 5+推荐使用webpack serve替代webpack-dev-server,更新package.json的scripts:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack serve --mode development", "build": "webpack --mode production" }
3. 确认静态资源路径与HTML引入
确保根目录下的index.html正确引入打包后的out.js:
<script src="./build/out.js"></script>
当前devServer的static配置已指向根目录,可保证静态资源正常访问。
4. 确认Babel配置有效性
现有Babel配置通过@babel/preset-env已支持ES6转译,无需额外调整,可正常处理app.js中的ES6代码。
修改后的完整webpack.config.js:
const path = require("path"); const entryPath = "."; module.exports = { mode: "development", entry: `./${entryPath}/js/app.js`, output: { filename: "out.js", path: path.resolve(__dirname, `${entryPath}/build`), }, devServer: { static: path.join(__dirname, `${entryPath}`), hot: true, compress: true, port: 3001, open: true, headers: { "Access-Control-Allow-Origin": "*" }, }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"], }, }, }, ], }, };
完成以上调整后,执行npm start启动DevServer,修改app.js即可触发自动重载,同时ES6代码可被正常转译打包。
内容的提问来源于stack exchange,提问作者kamill
相关产品推荐
相关产品推荐

