Using webpack and React to load images

时间秒杀一切 提交于 2019-12-11 06:14:43

问题


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/


回答1:


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.



来源:https://stackoverflow.com/questions/41775698/using-webpack-and-react-to-load-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!