【问题标题】:File-loader creating 2 images and linking the wrong one文件加载器创建 2 个图像并链接错误的图像
【发布时间】:2021-11-07 21:03:34
【问题描述】:

file-loader 正在我的构建文件夹中创建两个单独的图像。一个是正​​确命名并保存在正确的路径中,另一个是命名为 [hash].png(这是默认值)并存储在 build,而不是 build/images 中。第二个不正确的文件是0字节;这是构建文件夹中最终 index.html 文件中链接的那个。我已经定义了 outputPath 和 publicPath。 publicPath 似乎并没有真正做任何事情,不管我放了什么。我误解了它的作用吗?

module.exports = {
    entry: {
        index: './app/main.js',
        vendor: './app/vendor.js'
    },
    output: {
        path: path.resolve(__dirname, './build'),
        filename: '[name].[contenthash].js',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: [/node_modules/, /api/, /tests/, /coverage/],
                use: 'babel-loader'
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            },
            {
                test: /\.html$/,
                use: 'html-loader'
            },
            {
                test: /\.(svg|png|jpg|gif)$/,
                use:{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[hash].[ext]',
                        outputPath: 'images/',
                        publicPath: 'images/'
                    }
                }
            },
        ]        
    },
    plugins: [
        new HtmlWebpackPlugin({ template: './app/index.html' }), 
        new CleanWebpackPlugin()
    ]
};

最终 html 中的图片链接:

<img src="465107fe07e3ec18a463.png">

另一个有相同问题但没有得到任何答案的帖子: Webpack, I am trying to use file loader to load images but whenever i run build i get 2 images not 1 and the one linking to the html file is wrong

【问题讨论】:

    标签: html image webpack webpack-file-loader file-loader


    【解决方案1】:

    我终于明白了。从 Webpack 5.0 开始,这可以在根本不安装加载器的情况下处理。所以file-loader、url-loader、raw-loader等现在都已经过时了。

    https://webpack.js.org/guides/asset-modules/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多