Webpack 5:为什么 MiniCssExtractPlugin.loader 不让 HMR 工作?

问题描述

谁能解释一下为什么 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'

对此有所帮助,但就我而言,它也无法解决此问题。

解决方法

为了避免这种情况,有必要使编译文件的名称不带 hash 或 contenthash