vite打包,本地图片404

246 阅读1分钟

场景:图片存储在本地,通过json文件读取数据,展示图片,开发环境正常,打包之后404。
解决方案:import.meta.glob

```
function getLocalImgs(path) {
    const modules = import.meta.glob("/src/assets/imgs/*",{ eager: true })
    return modules[path].default
}


<img :src="proxy.$getLocalImgs(imgUrl)" class="image" />

注意:

  1. imgs文件下不能有文件夹,因为读取不到;
  2. 其中 proxy.$getLocalImgs 是挂载到了全局。

挂载全局方法如下

//main.js
import getLocalImgs from "./plus/useLocalImgs.js"
app.config.globalProperties.$getLocalImgs = getLocalImgs

// 调用
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
<img :src="proxy.$getLocalImgs(imgUrl)" class="image" />