webpack打包html引入图片问题

我在html里面使用img,然后通过file-loader,html-withimg-loader,html-webpack-plugin去打包
html代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <img src="./logo.jpg" alt="" srcset="">
  </div>
</body>
</html>

webpack.config.js

'use strict';

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name]_[contentHash:8].js'
    },
    mode: 'production',
    stats: { children: false },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ]
            },
            {    
                test: /\.(png|svg|jpg|gif)$/,
                use: ["file-loader"]
            },
            {
                test: /\.html$/,
                use: ["html-withimg-loader"]
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'src/index.html'),
            filename: 'index.html',
            chunks: '[index]',
            inject: true,
            minify: {
                html5: true,
                collapseWhitespace: true,
                preserveLineBreaks: false,
                minifyCSS: true,
                minifyJS: true,
                removeComments: false
            }
        }),
    ],

};

图片有打包成功,但是有报错,html生成错误
image.png

版本webapck:4.41.2,file-loader:5.0.2,html-withimg-loader:0.1.16,html-webpack-plugin:3.2.0

已解决 悬赏分:50 - 解决时间 2021-11-26 20:28
反对 0举报 0 收藏 0

回答2

最佳
  • @

    "file-loader": "^4.2.0" 是好的

    如果使用"file-loader": "^5.0.2",在webpack.config.js里修改配置项:

                {    
                    test: /\.(png|svg|jpg|gif)$/,
                    use:[
                        {
                            loader: "file-loader",
                            options: {
                                esModule: false,
                            },
                        }
                    ]
                },

    设置esModule为false

    参见:
    image.png

    支持 0 反对 0 举报
    2021-11-26 07:11
  • @

    使用html-withimg-loader后htmlWebpackPlugin无法解析?

    支持 0 反对 0 举报
    2021-11-26 07:55