Appearance
封装获取静态资源路径的函数
vite 项目中如果我们配置了路径别名后,除了模板与import
导入时可以使用外,如果我们想在其他 js 代码中使用,会出现 js 运行时不支持路径别名的访问,所以需要我们自己手动重定向到对应目录中去。我们可以使用URL
api 来拼接出资源路径。
URL 代码示例
ts
const url = new URL("user", "http://www.baidu.com");
console.log(url.href); // http://www.baidu.com/user
const url = new URL("user", "http://www.baidu.com");
console.log(url.href); // http://www.baidu.com/user
定义
ts
/**
* 获取静态资源
* @param path 从assets根路径开始
*/
export function getAssets(path: string) {
// 此处的路径是以该函数定义的文件为相对路径
return new URL(`../../assets/${path}`, import.meta.url).href;
}
/**
* 获取静态资源
* @param path 从assets根路径开始
*/
export function getAssets(path: string) {
// 此处的路径是以该函数定义的文件为相对路径
return new URL(`../../assets/${path}`, import.meta.url).href;
}
使用
ts
const navList = [
{
title: "Home",
activeIconName: getAssets("icon/footer/home_active.png"),
iconName: getAssets("icon/footer/home.png"),
path: "/",
},
{
title: "Subscribe",
activeIconName: getAssets("icon/footer/subscribe_active.png"),
iconName: getAssets("icon/footer/subscribe.png"),
path: "/subscribe",
},
{
title: "My",
activeIconName: getAssets("icon/footer/my_active.png"),
iconName: getAssets("icon/footer/my.png"),
path: "/my",
},
];
const navList = [
{
title: "Home",
activeIconName: getAssets("icon/footer/home_active.png"),
iconName: getAssets("icon/footer/home.png"),
path: "/",
},
{
title: "Subscribe",
activeIconName: getAssets("icon/footer/subscribe_active.png"),
iconName: getAssets("icon/footer/subscribe.png"),
path: "/subscribe",
},
{
title: "My",
activeIconName: getAssets("icon/footer/my_active.png"),
iconName: getAssets("icon/footer/my.png"),
path: "/my",
},
];