使用import.meta.url实现传递路径动态加载资源

背景

在开发 Vue 项目时,动态路由是必要功能,从后端或本地获取到菜单列表的 component 都是是字符串,要转成动态加载方式。因为项目用到了 monorepo,有多个子模块,但有的子模块是直接被引用的,不会单独打包,没有 vite.config.ts 配置,也就没有 @ 别名,转换路由的功能又抽成公共函数,这时模块路径就不好处理,因为动态导入路径默认是相对当前模块的。从别名设置处获得灵感,使用 import.meta.urlimport.meta.url 返回当前模块的完整 URL,在调用的地方把 import.meta.url 当作参数传递给转换路由的函数,这样在函数中就可以得到该子模块的相对路径了,相当于传递了相对路径。

示例

调用处

typescript 复制代码
setAsyncRouter(import.meta.url, 'monitor')

转换函数

typescript 复制代码
const setAsyncRouter = (path: string, module: string) => {
		const menuStore = useMenuStore();
		const baseUrl = new URL("./", path).href;
		const baseRouter: any[] = [
			{
				path: `/${module}`,,
				name: "layout",
				component: "views/layout/index.vue",
				meta: {
					title: "底层layout",
				},
				children: [],
			},
		];
		const menus = menuStore.asyncMenus;
		const asyncRouter = getMenuList(menus, module););
		baseRouter[0].children = asyncRouter;
		asyncRouterHandle(baseRouter, baseUrl);
	};
typescript 复制代码
function asyncRouterHandle(asyncRouter: Router[], path: string) {
	asyncRouter.forEach((item) => {
		if (item.component) {
			const component = `${path}${item.component}`;
			item.component = () => import(component); // 这里要先定义变量再用
		}
		if (item.children) {
			asyncRouterHandle(item.children, path);
		}
	});
}

需要传递路径的地方都可以这么用。

相关推荐
problc2 小时前
OpenClaw 的前端用的React还是Vue?
前端·vue.js·react.js
凰轮2 小时前
vue实现大文件切片上传
vue.js
冰暮流星2 小时前
javascript里面的return语句讲解
开发语言·前端·javascript
步步为营DotNet2 小时前
使用.NET 11的Native AOT提升应用性能
java·前端·.net
Never_Satisfied2 小时前
在JavaScript / HTML中,监听鼠标滚动事件
javascript·html·计算机外设
左耳咚2 小时前
Claude Code 记忆系统与 CLAUDE.md
前端·人工智能·claude
予你@。2 小时前
Vue 实现:点击按钮将 HTML 导出为图片(完整教程)
javascript·vue.js·html
早點睡3902 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-svg (CAPI版本)
javascript·react native·react.js
喵叔哟2 小时前
12-调用OpenAI-API
前端·人工智能·.net