ZarifS
ZarifS

Reputation: 477

Using webpack and url-loader to load inline images in React

I need to use a inline style and pass in the url of a image file. I do it like this:

let url = `url(${this.state.logo})`
        var cardStyle = {
            backgroundImage: url,
            backgroundSize: '200px 50px',
            backgroundRepeat: 'no-repeat'
        }

Then use it in div like this:

<div className='work-card' style={cardStyle}></div>

The url would be a property passed in something like '../images/logos/ciena.png', which is the path to the image relative to the component.

However when i run the app using webpack i get a 404 on the image. The error comes in like this: http://localhost:8080/images/logos/ciena.png 404 (Not Found)

I am using url-loader to load images and it is working fine when using images in scss files however inline it is not working and I don't know how to fix it.

My Webpack config:

const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlWebpackPlugin = new HtmlWebPackPlugin({template: "./src/index.html", filename: "./index.html"});

module.exports = {
    output: {
        publicPath: "/"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }, { // regular scss files to css
                test: /\.scss$/,
                loader: 'style-loader!css-loader!sass-loader'
            }, {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'url-loader',
                options: {
                    limit: 8000, // Convert images < 8kb to base64 strings
                    name: 'images/[name].[ext]'
                }
            }, {
                test: /\.(pdf|docx)$/,
                loader: 'file-loader?name=documents/[name].[ext]',
            }
        ]
    },
    devServer: {
        historyApiFallback: true
    },
    plugins: [htmlWebpackPlugin]
};

Thank you for your help!

Upvotes: 3

Views: 8275

Answers (1)

Soroush Chehresa
Soroush Chehresa

Reputation: 5678

To resolve your problem update url-loader config to:

{
  test: /\.(gif|png|jpg|svg)(\?.*$|$)/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192,
        name: '[name].[ext]',
        publicPath: 'images/'
      },
    },
  ],
},

Upvotes: 2

Related Questions