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

阅读 3.6k
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,
                        },
                    }
                ]
            },

设置esModulefalse

参见:
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题