在webpack中我們只需要
component: () => import(`@/views${r.component}`)
但是在vite中锻离,我們需要官方推薦的import.meta.glob引入動態(tài)文件來解決這個問題。
const modules=import.meta.glob("../views/**/**.vue")
component: modules[`../views${r.component}`],
完整代碼
import layout from "@/layout/index.vue";
import type { menuItem } from "@/types/user";
const modules = import.meta.glob("../views/**/**.vue");
export function generateRouter(userRouters: any) {
let newRouters;
newRouters = userRouters.map((r: any) => {
const routeObj = {
id: "",
path: "/",
component: layout,
children: [] as menuItem[],
};
routeObj.children = [];
let routes: any = {
path: r.routePath,
icon: r.icon,
meta: {
title: r?.name,
},
component: modules[`../views${r.component}`],
};
routeObj.children.push(routes);
return routeObj;
});
return newRouters;
}