我正在尝试使 webpack 的 HMR/Live 重新加载功能正常工作,但虽然“观看”文件似乎有效,但浏览器不会刷新。
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
entry: './index.js',
target: 'web',
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.htm$/,
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
},
devServer: {
port: 9000,
index: './homepage.htm',
host: 'test.local',
contentBase: path.join(__dirname, 'dist'),
hot: true,
watchContentBase: true
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css'
}),
]
}
package.json:
"devDependencies": {
"css-loader": "^6.1.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"sass": "^1.35.2",
"sass-loader": "^12.1.0",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
命令:
"serve": "webpack serve --mode=development --env=development"
webpack 观看和重新编译时的输出为:
ℹ 「wdm」: Compiling...
ℹ 「wdm」: assets by status 880 bytes [cached] 1 asset
assets by chunk 422 KiB (name: main)
asset main.js 420 KiB [emitted] (name: main)
asset main.ddfc292cf943c7bbaef7.hot-update.js 1.56 KiB [emitted] [immutable] [hmr] (name: main)
asset style.css 410 bytes [emitted] (name: main)
asset main.ddfc292cf943c7bbaef7.hot-update.json 28 bytes [emitted] [immutable] [hmr]
Entrypoint main 422 KiB (880 bytes) = style.css 410 bytes main.js 420 KiB main.ddfc292cf943c7bbaef7.hot-update.js 1.56 KiB 1 auxiliary asset
cached modules 340 KiB [cached] 36 modules
runtime modules 29.3 KiB 14 modules
modules by layer 372 bytes (javascript) 77 bytes (css/mini-extract)
./src/style.scss 372 bytes [built] [code generated]
css ./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/style.scss 77 bytes [built] [code generated]
webpack 5.45.1 compiled successfully in 99 ms
ℹ 「wdm」: Compiled successfully.
值得注意的是,没有 [HMR]
条目(尽管它通知我热更新文件已更新,但我认为我应该看到它。)感谢任何帮助!
答案 0 :(得分:0)
您最初应该在浏览器控制台中看到这些消息:
[Log] [HMR] Waiting for update signal from WDS...
[Info] [WDS] Hot Module Replacement enabled.
[Info] [WDS] Live Reloading enabled.
您需要通过将这些行放在 index.js 中来为 hmr 启用代码:
if (module.hot) {
module.hot.accept();
}
在此处查找文档: https://webpack.js.org/guides/hot-module-replacement/