简体   繁体   English

使用webpack和React加载图像

[英]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 我是使用React和webpack的新手,我似乎无法将我的资产目录中的图像加载到我需要的反应文件中。它显示在本地服务器上,但是当我在我的github页面上运行它时,图像没有正确加载

this code works fine on the local server. 此代码在本地服务器上正常工作。

Portfolio.jsx Portfolio.jsx

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

Is there any way to require my assets directory from that React file ? 有没有办法从该React文件中要求我的资产目录?

Here is my gh-page : https://jcook894.github.io/Portfolio/ 这是我的gh页面: https//jcook894.github.io/Portfolio/

You can use the require keyword so that it will be properly resolved. 您可以使用require关键字以便正确解析它。

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. 为此,您需要在webpack配置文件中加载文件加载器。 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. 请注意,对于jpep,jpg,png和gif,它会使用您的filename.ext将文件复制到dist目录。 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. 如果要在dist文件夹中获取图像,但路径不正确,请检查加载器中的pathName参数修复。

I haven't tested it with your code, but this is the general idea. 我没有用你的代码测试它,但这是一般的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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