我正在使用webpack with react,我通常导入并使用我的图像:
import CalNotices from 'assets/img/calendar-notices.png';
<img className='img-center' role='presentation' src={CalNotices}/>
工作正常,当我进行生产构建时,这些图像区域整齐地放入适当的文件夹中。
然而,有时候,我想将图像用作背景,并将其用作:
const divStyle = {
backgroundImage: `url(${item.logo})`,
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center'
}
<div className='image-holder' style={divStyle}></div>
item.logo是图像的绝对路径。
这在dev中运行良好,但是当我进行prod构建时,这些图像显然是丢失的,因为它们没有被webpack图像加载器拾取。我该怎么做呢?
我的图片加载程序配置
{
test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)(\?.*)?$/,
include: [paths.appSrc, paths.appNodeModules],
loader: 'file',
query: {
name: 'static/media/[name].[ext]'
}
},
答案 0 :(得分:2)
根据您的评论(所有图片都在/src/assets/img/logos
中),您可以利用webpack的require.context功能在构建时捆绑整个徽标文件夹:
// causes webpack to find and bundle *all* files in logos or one of its subfolders.
const logoContext = require.context("assets/img/logos", true, /\.(png|jpg)$/);
// later...in your render() method
// assumes item.logo is a path relative to the logos folder
// example: "credit-card-xxx.jpg" or "./credit-card-xxx.jpg"
const logoUrl = logoContext.resolve(item.logo);