0

file-loader is creating two separate images in my build folder. One is the named correctly and saved in the correct path, the other is named [hash].png (which is the default) and is stored in build, not build/images. The second incorrect file is 0 bytes; this is the one being linked in the final index.html file in the build folder. I've defined both outputPath and publicPath. publicPath doesn't seem to actually do anything though, regardless of what I put there. Am I misunderstanding what it does?

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()
    ]
};

Image link in final html:

<img src="465107fe07e3ec18a463.png">

Another post with the same issue that didn't get any answers: 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

William
  • 77
  • 8

3 Answers3

0

I eventually figured it out. As of Webpack 5.0, this can be handled without installing a loader at all. So file-loader, url-loader, raw-loader, etc. are now obsolete.

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

William
  • 77
  • 8
0

This is a problem of file-loader v6. I solved this with the way adding esModule option.

Both html-loader, css-loader and loader that using image url need the esModule option false.

Or you should use the file-loader except v6.

{
  loader: 'css-loader',
  options: {
    esModule: false
  }
},
-1
        {
            test: /\.(png|svg|jpg|jpeg|gif)$/i,
            type: 'asset/resource',
        },
  • 4
    Code only answers are considered low quality. Without sufficient explaination, your answer is hard to understand. If the OP can't understand your answer, then he also won't be able to reproduce your possible solution. As such it would be worthless to him/her. Please add a sufficient explaination of your possible solution. – tacoshy Feb 24 '22 at 08:09