Webpack devServer 4.x热更新失效排查及静态HTML热更新配置咨询
问题1:src目录JS修改编译后浏览器不自动刷新的根因与修复
根因
- webpack-dev-server v4默认仅监听
devServer.static配置的目录下的文件变更,你配置的static目录是dist,src目录的文件变更只会触发编译,devServer没有主动推送刷新信号给浏览器。 - Windows 10下通过Git Bash运行时,原生的文件系统监听机制容易出现异常,导致变更通知丢失。
static.directory使用相对路径存在路径识别错误的可能。
修复方案
修改webpack.config.js的devServer配置项如下:
devServer: { static: { directory: path.resolve(__dirname, 'dist'), // 改为绝对路径避免识别错误 watch: true }, liveReload: true, // 显式开启自动刷新能力 watchFiles: ['src/**/*'], // 监听src目录下所有文件变更,变更后主动触发浏览器刷新 // Windows环境下添加以下配置解决原生监听失效问题 watchOptions: { poll: 1000, // 每1秒轮询检查文件变更 aggregateTimeout: 300, // 防抖配置,300ms内多次变更只触发一次刷新 }, open: true // 可将package.json start命令里的--open参数移除,统一放在配置中管理 },
package.json中的"start": "webpack serve --open"配置本身没有问题,只要没有额外添加--no-live-reload这类禁用参数即可正常使用。
问题2:根目录静态index.html修改自动热重载的配置调整
要实现根目录下的静态index.html修改后自动刷新,做两处调整即可:
- 在
devServer.watchFiles数组中添加根目录html的匹配规则 - 如果你使用html-webpack-plugin生成页面,需要指定该文件为模板,否则修改的html不会被编译到dist目录,刷新也不会生效
修改后的完整对应配置如下:
// devServer部分 devServer: { static: { directory: path.resolve(__dirname, 'dist'), watch: true }, liveReload: true, watchFiles: ['src/**/*', './index.html'], // 新增根目录index.html的监听规则 watchOptions: { poll: 1000, aggregateTimeout: 300, }, }, // plugins部分 plugins: [ new HtmlWebpackPlugin({ title: 'Output Management', template: './index.html' // 指定根目录的index.html为编译模板 }), ],
如果你的根目录index.html不需要被html-webpack-plugin处理,是纯静态资源,也可以把根目录添加到static配置中:
devServer: { static: [ { directory: path.resolve(__dirname, 'dist'), watch: true }, { directory: __dirname, watch: false } // 根目录作为静态资源目录,不需要监听整个根目录避免性能损耗,仅在watchFiles里监听index.html即可 ] }
内容的提问来源于stack exchange,提问作者Karl
相关产品推荐
相关产品推荐

