1

I'm using Webpack and trying to use a png-image to be shown in my Firefox browser. The problem is that Webpack creates two images in dist folder, one of them has probably an error and can't be shown neither on my laptop nor in browser ("An error occurred while loading the image") and Webpack tries to use it and not another one that should work.

My webpack.config.js has the following modules:

module: {
    rules: [{
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
        },
        {
            test: /\.(jpe?g|png|gif|svg)$/,
            use: ['file-loader']

        }
    ]
}

In styles.css I used background-image:

.logo {
background-image: url('../assets/foto.png');
background-size: cover;
height: 200px;
width: 200px;
margin: 0 auto;}

In index.html I use a div container:

 <div class="logo"></div>

Here is the structure of my project:

 dist/ 
   - h74g3ffgf3ff34h76.png
   - analytics.54t54gg4.js
   - ab0d12j489gh4igh8.png
   - index.html
   - main.h74rg34u73f.js
 src/
     assets/
       - foto.png
     styles/
       - styles.css
   - analytics.js
   - index.html
   - script.js
- package-lock.json
- package.json
- webpack.config.js
     

Versions:

  • Webpack: 5.53.0
  • css-loader: 6.3.0
  • file-loader: 6.2.0

I assume there is a problem with the path to the foto.png, but I couldn't figure out how can I fix this. Absolute and relative paths didn't work.

Why does Webpack create two images in dist folder and use the one, that is broken? What am I doing wrong?

Anna R.
  • 81
  • 12
  • Have you tried `url-loader` package? I think it is similar to https://stackoverflow.com/questions/35369419/how-to-use-images-in-css-with-webpack – the_spectator Sep 22 '21 at 10:54
  • @the_spectator thanks for your comment! yes, I tried it but unfortunately it didn't help. With url-loader Webpack created just one image in dist folder, but it is also broken and my browser doesn't show it. With url-loader I also get another very long name for my image in console.log like `"img":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAAD...`. And it doesn't match the name of the image in my dist folder. Do you probably have an idea why? – Anna R. Sep 22 '21 at 11:27

1 Answers1

3

I solved the problem by using Asset Modules instead of url-loader and file-loader. So the code looks like this:

{
    test: /\.(jpe?g|png|gif|svg)$/,
    type: 'asset/resource'

 }
Anna R.
  • 81
  • 12
  • Thanks a lot. I was searching for hours, it worked for me. In my case, I give src to img like src="../images/cat.png", then webpack created two image one of them into root folder one of them into /images/ folder. The img tag was using the photo that is in the root folder and it was broken somehow. – Ugur Kellecioglu Aug 05 '22 at 13:32