vite_ts_auto/src/router/module/pageRoutes.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-05-08 13:43:24 +08:00
import { routeFilenameHelper } from '@/utils/file/routeFileUtil';
import { RouteRecordRaw } from 'vue-router';
// * 最终路由
const routeMap: Record<string, RouteRecordRaw> = {};
// * 所有处理的路由
const contexts = [
{ context: import.meta.glob("@/views/**/*.vue", { eager: true, import: "default", }), isIndex: true },
{ context: import.meta.glob("@/views/**/page.ts", { eager: true, import: "default", }), isIndex: false },
];
/**
*
* @param context
* @param isIndex
*/
const createRouteList = (context: any, isIndex: boolean) => {
Object.entries(context).forEach(([filePath, exportRouteConfig]) => {
const fileInfo = routeFilenameHelper(filePath);
// 组装路由对象
const route: any = {
name: fileInfo?.name,
path: fileInfo!.path,
component: isIndex ? () => import(fileInfo!.filePath) : undefined,
};
// 初始化赋值
if (isIndex) {
routeMap[route.path] = route;
} else {
// 导出当前存在的路由并重新赋值
const existingRoute = routeMap[route.path];
if (existingRoute) {
routeMap[route.path] = { ...existingRoute, ...(exportRouteConfig as any) };
}
}
})
};
// * 生成路由信息
contexts.forEach(({ context, isIndex }) => createRouteList(context, isIndex))
export const pageRoutes: Array<RouteRecordRaw> = [...Object.values(routeMap)];