webpack5 热更新后报错:Module parse failed: Unexpected character '�'

1,384 阅读1分钟

问题

如果你的 webpack5 项目在构建成功,修改代码 热更新 执行完,所有图片报下列错误:

 error  in ./src/pages/404/error.png

Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

image.png

解决办法

把你的webpack版本降级到:

webpack: ^5.74.0

猜测原因

最新版本 webpack: ^5.83.1 的在热更新时 asset 模块没有执行或者出问题

// webpack.config.js
module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        // webpack5 内置了 asset 模块, 用来代替 file-loader & url-loader & raw-loader 处理静态资源
        test: /.(png|jpg|gif|jpeg|svga)/,
        type: 'asset',
        parser: {
            dataUrlCondition: {
                maxSize: 3 * 1024, // base64规则 改为 < 3k
            },
        },
        generator: {
            filename: 'images/\[file]?\[contenthash:5]',
        },
      },
    ]
  }
}