webpack-dev-server not hot reloading (webpack 5)



我是webpack的新手,所以我在网上看了一些webpack 5教程和文档,但我不知道如何解决这个问题

文件结构:

dist
node_modules
src
modules
js files
style
style.css
index.html
index.js
package.json
package-lock.json
webpack.config.js

Webpack配置:

const { appendFile } = require("fs");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: 'development', 
entry: {
main: path.resolve(__dirname,'src/index.js'),
},
output: {
path:path.resolve(__dirname,'dist'),
filename: 'app.bundle.js',
hashFunction: 'xxhash64',
},
devtool: 'inline-source-map',
devServer: {
static: {
directory:path.resolve(__dirname,'dist'),
watch:true,
},
port: 8080,
open: true,
hot: true,
},
//loaders
module: {
rules: [
{test: /.css$/, use:['style-loader','css-loader']}
]
},
//plugins
plugins: [new HtmlWebpackPlugin({
title: 'To Do List',
filename: 'index.html',
template: path.resolve(__dirname,"./src/index.html")
})]
}

当我运行"npm运行dev"我的网页打开的HTML/CSS/JS,但没有改变(没有重新编译发生),当我改变我的代码。

另外,另一个奇怪的问题是,我的import语句在保存时在index.js文件中被删除,不确定这是否与此有关,或者只是一个VScode问题

你有一个地方要纠正你的devServer.static.directory:它应该是./,而不是dist。以下是devServer的设置集,它为我工作:

devServer: {
port: 8080,
hot: "only",
static: {
directory: path.join(__dirname, './'),
serveIndex: true,
},
},

我也在与HMR作斗争,结果几乎一无所获,真是令人失望,除非我用这种方法使它工作:

devServer: {
port: 8080,
hot: false,
liveReload: true,
watchFiles: ['dist/**/*'],
open: ['http://localhost:8080/html/index.html']
}

基本上我切换到liverload来实现相同的结果,现在它工作了。

注:你不需要使用'打开',但我的html位于dist/html/index.html,我使用链接打开窗口与该html

最新更新