vue3+vite项目,动态svg build后,线上找不到图片问题
问题-:变量中相对路径引入,文件找不到
好多时候,我们使用是svg都是动态的,就会有不同的src,这时,src就需要是一个动态的变量。我们按常规配置:
const productList = {
logo: '../assets/svg/xxx.svg',
}
模板使用
<a-menu-item v-for="item in productList" :key="item.id">
<template #icon>
<img :src="item.logo" style="width: 20px; "/>
</template>
</a-menu-item>
上面这样使用,在本地都是找不到文件的。
但是直接在模板中这样使用是可以的
<a-menu-item v-for="item in productList" :key="item.id">
<template #icon>
<img src="../assets/svg/xxx.svg" style="width: 20px; "/>
</template>
</a-menu-item>
这是因为,把变量解析成了字符串,没有按路径去查找。
问题二:采用new URL() 方式,本地能找到,build后找不到
const name = 'xxx'
const productList = [{
logo: new URL(`../assets/svg/${name}.svg`, import.meta.url).href,
}]
模板使用
<a-menu-item v-for="item in productList" :key="item.id">
<template #icon>
<img :src="item.logo" style="width: 20px; "/>
</template>
</a-menu-item>
上述这样使用,在本地是没有问题的,但是部署到线上就找不到了,查看源代码,线上把src最终解析成了[Object Object],可见打包后,没有去解析出真正的路径。
费了老半天劲,各种方式去试过,最后在vite文档中找到了答案;
URL方式,不能使用模板字符串,改为字符串就行
const productList = [{
logo: new URL(`../assets/svg/xxx.svg`, import.meta.url).href,
}]