简体   繁体   中英

Using webpack and React to load images

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM