Search code examples
javascriptwebpackwebpack-file-loader

Webpack. Image loading failed


Using webpack for the first time. Can't load images in there. Tried a LOT of things to fix it, but... I included my images in html through img src. I also did import in index.js:

    import backGround from '../img/bg.jpg';
    const bgImg = document.getElementById('bg');
    bgImg.src = backGround;

So I got this kind of error: ERROR in ./src/img/bg.jpg 1:0 Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type

I can also show you my config:

    {
    test: /\.(png|svg|jpg|gif)$/,
    use: [
      'file-loader'
    ],
  },

Solution

  • Yow broh, you need to use url-loader File loader is for html files and stuff

     // "url" loader works like "file" loader except that it embeds assets
                // smaller than specified limit in bytes as data URLs to avoid requests.
                // A missing `test` is equivalent to a match.
                {
                  test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
                  loader: require.resolve('url-loader'),
                  options: {
                    limit: imageInlineSizeLimit,
                    name: 'static/media/[name].[hash:8].[ext]',
                  },
                },
    …..
    // More loaders
    …..
    
                {
                  loader: require.resolve("file-loader"),
    
                  exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
                  options: {
                    name: "static/media/[name].[hash:8].[ext]",
                  },
                },
    

    Make sure to put file loader at the end