webpack-dev-server不热重载(webpack 5)

4

我对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 run dev”时,我的网页会打开HTML/CSS/JS,但当我更改代码时没有任何变化(不重新编译)。另外,另一个奇怪的问题是,我的index.js文件中的导入语句在保存时被删除,不确定是否与这个问题有关或只是一个VScode的问题。

1
可能会在这里找到你的答案 https://dev59.com/k1kT5IYBdhLWcg3wG70_。我个人建议从将“contentBase”添加到您的选项开始。 - user16435030
2
@Matriarx 这个问题是关于 webpack 5 的,但是 contentBase 在版本 4 中已经被移除了。 - Craig McIlwee
2个回答

2

你在 devServer.static.directory 中有一个需要更正的地方:应该是 ./,而不是 dist。以下是适用于我的 devServer 设置:

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

不确定是否只有我遇到了这个问题,但是在尝试您的方法时,我遇到了“缓存”重新加载的情况。就像更改并不总是刷新我的页面,有时候它会刷新。我的方法使用liveReload每次在我进行更改时都会刷新页面,您的方法似乎有些缺失? - zippelgazz

2

我也曾为HMR苦苦挣扎,最终几乎一无所获,但是我通过以下方法使其正常工作:

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

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

P.S. 你不需要使用'open',但是我的html文件位于 dist/html/index.html,我使用链接打开窗口并访问该html文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接