Search code examples
javascriptwebpackwebpack-file-loader

How to include images from CSS (backgrounds and etc.) to build folder using webpack?


I'm trying to use file loader to process images and include them into my build folder.

Images which are inside html files appear in build but images from styles not.

I keep my webpack config splitted into 2 files and use webpack merge module to merge them.

This is how i configure css processing:

exports.loadCSS = function (paths) {
    return {
        module: {
            rules: [{
                test: /\.scss$/,
                include: paths.app,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            root: paths.root
                        }
                    },
                    'postcss-loader',
                    'sass-loader'
                ]
            }]
        }
    };
};

And this is file loader configuration:

            {
                test: /\.(jpg|png|svg)$/,
                loader: 'file-loader?name=[path][name].[hash].[ext]'
            }

Piece of scss:

.img-from-styles {
  width: 100px;
  height: 100px;
  background: url('/imgs/imgInStyles.jpg');
}

Here is project itself containing full configuration


Solution

  • You need to use url-loader Install it

    npm install url-loader --save-dev
    

    How use it

    {
        test: /\.(png|jpg|jpeg|gif)$/,
        loader: 'url-loader?limit=10000'
     }
    

    Now webpack will be able to resolve your url from your styles

    Update

    Webpack (css-loader) need exact file path so it can resolve the file or url for you.