无效的代码块(该代码在vite 5版本有效):
/**
* 获取图片的地址
* @param path 基于assets/images/文件夹下的位置
* @returns 图片地址
*/
export function getImageUrl(path: string) {
return new URL(`../assets/images/${path}`, import.meta.url).href;
}
问题:当资源文件存放在多层文件夹下,此时 path 路径含有多层目录,无法获得资源地址。
例:
此时 path = '404_images/404_cloud.png'
原因:
vite6相比于vite5,path中不再包括子目录的文件。
解决方案:
<img :src="getImageUrl('404_images/404.png')" alt="404" />
/**
* 根据图片路径获取图片地址(基于 assets/images 路径)
* @param path 图片路径
* @returns 图片地址
*/
export function getImageUrl(path: string) {
const pathArr = path.split('/');
switch (pathArr.length) {
case 1:
return new URL(`/src/assets/images/${path}`, import.meta.url).href;
case 2:
return new URL(`/src/assets/images/${pathArr[0]}/${pathArr[1]}`, import.meta.url).href;
case 3:
return new URL(
`/src/assets/images/${pathArr[0]}/${pathArr[1]}/${pathArr[2]}`,
import.meta.url
).href;
default:
throw new Error('Invalid path');
}
}