最近小编在工作要开发一个游戏官网,但是在其中遇到了一个问题,所有游戏的相关数据都是excle表格,小编把他们转化成json文件后格式大致如下
{
"Game Name": "Fortune Tiger",
"Game UID": "xxxxxxxxxxxxx",
"Game Type": "Slot Game",
"img": "/src/assets/game_images/xxxx.png"
},
{
"Game Name": "Fortune Tiger2",
"Game UID": "xxxxxxxxxxxxx2",
"Game Type": "Slot Game",
"img": "/src/assets/game_images/xxxx2.png"
},
...
图片都是前端做静态资源保存,小编在这里就遇到了一个问题,就是我把所有游戏图片都是存放 src/assets (项目是vite5构建)文件夹下,在本地开发中import json文件获取图片都是能够正常展示,然而打包后图片丢失。
失败的原因是
我import json文件,但是并没有import图片,所以vite在打包时就不能知晓你需要这张图片,从而不会打包进去
解决方法如下:
第一种:json文件转成js,然后如下处理
import imgName from '@/assets/img/xxxx.png
{
"Game Name": "Fortune Tiger",
"Game UID": "xxxxxxxxxxxxx",
"Game Type": "Slot Game",
"img": imgName
},
缺点:如果像小编一样数据很多,这样就极其不方便,推荐少图时使用
第二种:图片资源存放到public文件下,然后通过new URL(icon,import.meta.url).href获取基于当前模块文件的相对路径 img 的完整 URL 地址
// 统一修改下json文件中图片路径如下
{
"Game Name": "Fortune Tiger",
"Game UID": "xxxxxxxxxxxxx",
"Game Type": "Slot Game",
"img": "/game_images/xxxx.png
}
<img v-lazy="getImageUrl(item.img)" alt="xxxx"/>
const getImageUrl = (img) => {
// console.log(img);
return new URL(icon, import.meta.url).href;
};
缺点: public文件下资源构建工具不会对资源进行压缩处理,如果资源很多包会很大