Skip to content Skip to sidebar Skip to footer

React Webpack Error Runtime Loading Of Image

I'm trying to load image at runtime in my react component. The images are stored inside src/assets folder var bg=require('../../../assets/plot1.jpg'); return(

Solution 1:

You're loading the image path dynamically, but in runtime and depending on your webpack config, your assets' paths in the bundle can be different from what's in your code.

Here's the default url-loader config in webpack for apps created by create-react-app:

{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve('file-loader'),
    options: {
        name: 'static/media/[name].[hash:8].[ext]',
    },
},

As you can see, files matching test will end up in static/media/[name].[hash:8].[ext]. So your background image will be saved as static/media/plot1.<some-hash>.jpg, which is different from the path you're passing to require via props, i.e. ../../../assets/plot1.jpg.

In the first case (var bg=require('../../../assets/plot1.jpg')), webpack sees the path, discovers the image, transforms its path, and assings the transformed path to bg. In the second case, the value of props.bg is unknown at compile time, so webpack doesn't handle it, which your image might not end up in the assets, or if it's there, it's path is not known to your runtime code. The main point is your code shouldn't rely on values that will be modified by bundlers like webpack during the transpile process.

You can put your image paths in an object that is processed by webpack, and then refer to the keys of that object to get the correct image. Here's an example:

Put this some where outside of your components, maybe in a config file or your entry point, wherever that makes the most sense:

constIMAGES = {
    bg1: require('<path-to-bg1>'),
    bg2: require('<path-to-bg2>'),
    ...
}

And then in the component:

constApp = (props) => {
    return<divstyle={{backgroundImage: "url(" + IMAGES[props.bgImg] + ")"}}>...</div>
}

Needless to say, you need to update your props to pass a key from IMAGES, instead of image paths.

Post a Comment for "React Webpack Error Runtime Loading Of Image"