1

Im new to using React and webpack and I cant seem to load the images from my assets directory to the react file I need it in. It displays on a local server but when I run it on my github page, the images arent loaded properly

this code works fine on the local server.

Portfolio.jsx

<img src="../assets/hood.png"/>

Is there any way to require my assets directory from that React file ?

Here is my gh-page : https://jcook894.github.io/Portfolio/

Jcook894
  • 37
  • 1
  • 8

1 Answers1

0

You can use the require keyword so that it will be properly resolved.

Something like this:

<img src={require('../assets/hood.png')}/>

For this to work, you need to have the file loader in your webpack config file. The configuration would look something like this:

module: {
    loaders: [
        {test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
        {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
        {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},
        {test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
        {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
        {test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
        {test: /\.ico$/, loader: 'file?name=[name].[ext]'},
        {test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'postcss', 'sass?sourceMap']},
        {test: /\.json$/, loader: "json"}
    ]
}

Notice that for jpep, jpg, png and gif, it will copy your file to the dist directory with your filename.ext. If you are getting your image in the dist folder, but the path is not correct, check for the pathName parameter fix in the loader.

I haven't tested it with your code, but this is the general idea.

Vivek V Dwivedi
  • 2,510
  • 2
  • 28
  • 39
  • Ive tried that and it give me this error ERROR in ./Portfolio.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ../assets/hood.png in /Users/juliancook/Portfolio @ ./Portfolio.jsx 24:42-71 – Jcook894 Jan 21 '17 at 04:29
  • so plugin the assets file name into the brackets where name is?? sorry, fairly new to using webpack – Jcook894 Jan 21 '17 at 04:51
  • Me too. But I faced this issue and this got it fixed. Would recommend you to look at https://github.com/coryhouse/react-slingshot which has a sample app created with very nice code quality and explanation. Owner of this repo also has a course on pluralsight. So you can check that out as well. – Vivek V Dwivedi Jan 21 '17 at 06:45