Vite 4.x + React 批量导入图片打包部署不显示?
vite4.x+React批量导入图片打包部署后不显示
vite.config.ts
中配置了assetsDir: 'statics',
打包之后的图片都在statics
目录中,导入图片的代码如下:
const images = import.meta.glob('@/assets/images/sample/rack/*.png')
const [imgUrlsMap, setImgUrlsMap] = useState<any>()
useEffect(() => {
Promise.all(
Object.keys(images).map(async (key) => {
const module: any = await images[key]();
const imageUrl = new URL(module.default, import.meta.url).href
return imageUrl;
})
).then((urls) => {
//
const ImgPathMap: any = urls.reduce((total: any, current: any) => {
return {
...total,
[current?.split('/')?.slice(-1)[0]?.split('.')[0]]: current// 值:http://localhost:3187/imh_view/src/assets/images/sample/rack/6.png
}
}, {})
setImgUrlsMap(ImgPathMap)
})
}, [])
{
rackSpeci?.map((item: any, idx: number) => (
<Col key={idx} style={{ display: 'inline-block', marginBottom: 10, marginRight: 6}}>
<img
className={styles.rackImg}
title={item.remark}
src={idx === imgIdx ? imgUrlsMap[`${item.rule}-${item.rule}`] : imgUrlsMap[item.rule]}
onClick={() => onSpeciSelect(item,idx)}
/>
<div style={{ textAlign: 'center'}}>{ item.name }</div>
<div style={{ textAlign: 'center'}}>({ item.rowNum + 'X' + item.columnNum })</div>
</Col>
))
}
得到的图片地址:http://localhost:3187/imh_view/src/assets/images/sample/rack/6.png
问题描述:在本地开发环境中图片能显示出来,打包部署之后不显示,审核元素查看img元素甚至没看到src属性,请问该如何解决呢
回复
1个回答

test
2024-06-19
图片不要用 vite 来处理,直接扔到 public 里。
上线之后如果需要处理,写服务器脚本或者在服务器端来做。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容