1

谁能解释一下为什么 MiniCssExtractPlugin.loader 不让 HMR 工作,我该如何解决?我创建了以下 webpack.config.js 文件:

const path = require ('path')
const HTMLWebpackPlugin = require ('html-webpack-plugin')
const MiniCssExtractPlugin = require ('mini-css-extract-plugin')

const cssLoaders = extra => {
    const loaders = [
        {
            loader: MiniCssExtractPlugin.loader,
            options: {
                publicPath: '',
            }
        },
        'css-loader'
    ]
    if (extra)
    {
        loaders.push(extra) 
    }
    return loaders
}

module.exports = {  
    entry: './src/js/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'app')
    },
    devServer: {
        port: 8000,
        hot: true
    },
    plugins:[
        new HTMLWebpackPlugin({
            template: './src/index.html'
        }),
        new MiniCssExtractPlugin({filename: '[name].[contenthash].css'})    
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: cssLoaders()
            }
        ]
    }       
}

保存新样式后,我在浏览器控制台中收到以下消息:

[Info] [WDS] App updated. Recompiling... (x2)
[Info] [WDS] App hot update...
[Log] [HMR] Checking for updates on the server...
[Log] [HMR] Updated modules:
[Log] [HMR]  - ./src/styles/style.css
[Log] [HMR] App is up to date.
[Log] [HMR] Reload all css

但实际上,为了看到变化,我必须重新加载页面。如果我换行

use: cssLoaders()

use: ['style-loader','css-loader']

HMR 真正开始工作。我在许多论坛上读到添加

target: 'web'

对此有帮助,但在我的情况下,它也不能解决这个问题。

4

1 回答 1

2

为避免这种情况,有必要使编译文件的名称不带散列或内容散列

于 2021-03-26T13:11:52.777 回答