Home > Enterprise >  Webpack doesn't show a png image in browser using background-image
Webpack doesn't show a png image in browser using background-image

Time:09-23

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?

CodePudding user response:

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

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

 }
  • Related