Nikita Vlasenko
Nikita Vlasenko

Reputation: 4352

Load images using React/Webpack

I set up the rule in webpack to load png images:

   {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
    }

That I found here: cannot load png files with webpack, unexpected character

Webpack seems to be working fine, giving no errors. So, I tried loading the png images paths that are located at app_folder/public/images/pca inside the render method:

  importAll = (r) => {
    return r.keys().map(r);
  }

  render() {
    const pca_images = this.importAll(require.context('../public/images/pca', 
    false, /\.(png|jpe?g|svg)$/));
      console.log('pca_images')
      console.log(pca_images)
...
}

When I launch the app I do not see any errors but the pca_images is an empty array. The component itself is located at app_folder/views/. I tried loading the images also directly like that:

 <img src={ require('../public/images/image1.png') } />

But whatever path I specify, it is just not working giving an error. I need to load all images from the folder app_folder/public/images/pca though, not just statically since I do not know the names of the images beforehand. Any suggestions would be greatly appreciated.

Upvotes: 1

Views: 9678

Answers (1)

Nikita Vlasenko
Nikita Vlasenko

Reputation: 4352

The solution that worked for me was to add the rule to the webpack.config.js:

{
    test: /\.(jpe?g|gif|png|svg)$/i,
    use: [
    {
      loader: 'url-loader',
      options: {
        limit: 10000
      }
    }
  ]
}

This rule I found here: ReactJS and images in public folder

Then I needed to run two commands in terminal:

npm install url-loader --save-dev
npm install file-loader --save-dev

And finally loading from the folder (see the question, render method) started working.

Upvotes: 10

Related Questions