使用webpack和React加载图像 [英] Using webpack and React to load images

查看:85
本文介绍了使用webpack和React加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用React和webpack不熟悉,我似乎无法将资产目录中的图像加载到需要它的react文件中.它显示在本地服务器上,但是当我在github页面上运行它时,图像arent正确加载

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

Portfolio.jsx

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

有什么办法可以从该React文件中请求我的资产目录吗?

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

这是我的gh页: https://jcook894.github.io/Portfolio/

推荐答案

您可以使用require关键字,以便正确解析它.

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

类似这样的东西:

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

为此,您需要在webpack配置文件中安装文件加载器.配置看起来像这样:

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"}
    ]
}

请注意,对于jpep,jpg,png和gif,它将使用filename.ext将文件复制到dist目录.如果要在dist文件夹中获取映像,但是路径不正确,请在加载程序中检查pathName参数是否修复.

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.

这篇关于使用webpack和React加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆