Search code examples
imagereactjswebpackurlloader

Cannot retrieve images in my react component


I am quite new at coding so please be indulgent... I searched a lot and I don't manage to get my issue fixed :(

I would like to get my images rendered through and html img tag. I saw that the best way in react is to import my images. Like this :

import avatar from './avatar.png';

export default class Connection extends React.Component {
  render () {
      return (
        <div>
          {this.props.user.firstname}&nbsp;{this.props.user.lastname}
          &nbsp;<img src={avatar} className='img-circle' />
          &nbsp;&nbsp;&nbsp;<a href='#' onClick={this.props.logout}>Déconnexion</a>
        </div>
      );
  }
}

I use the following webpack config to load these images :

module: {
    loaders: [
      { test: /\.jsx?$/, exclude: [/node_modules/], loader: 'babel' },
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader') },
      { test: /\.(png|gif|jpe?g|svg|jpg)$/i, loader: 'file-loader?hash=sha512&digest=hex&name=[path][name]-[hash].[ext]' },
      { test: /\.(png|gif|jpe?g|svg|jpg)$/i, loader: 'url-loader?limit=10000' }
    ]
  }

I see that webpack manage to load the jpg or png files but when it comes to display it, it seems that the file generated/copied is not available (ex: /MyApp/avatar-50b93a2df8aec266d7c8c1c0f5719d1b.png is not available).

I use the webpack dev server so I don't see my files bundled and the dist or build folder created.

Any idea of solving my issue ?

Thanks,

When using the require within the img tag I get the following error :

Module not found: Error: Cannot resolve 'file' or 'directory' ./avatar

I tried to get the extension in the webpack config but it does not solve anything :(

Here is my public path config in my webpack config :

output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js'
  }

Solution

  • To load images with Webpack you need to do:

    <img src={require('./avatar.jpg'})/>
    

    Webpack crawls through your application codebase, code gets bundled into a single file however files are not kept in the same structure, by calling require Webpack will do dependency management for you, in this case the file will move around and code will be injected so it is pointing to it's bundled location.