import { routeFilenameHelper } from '@/utils/file/routeFileUtil'; import _ from 'lodash'; import { RouteRecordRaw } from 'vue-router'; // * 最终路由 const routeMap: Record = {}; // * 所有处理的路由 const contexts = [ { context: import.meta.glob('@/views/**/index.vue', { eager: true, import: 'default' }), isIndex: true }, { context: import.meta.glob('@/views/**/page.ts', { eager: true, import: 'default' }), isIndex: false }, ]; /** * 构建路由信息 * @param context 上下文信息 * @param isIndex 是否第一次遍历 * @param route 路由内容 */ function buildRouteTree(context: any, isIndex: boolean, route: any) { // 遍历当前子路由 Object.entries(context).forEach(([filePath, _]) => { // 获取子路由下所有文件对象格式 const childrenFileInfo = routeFilenameHelper(filePath); // 组装子路由对象 const childrenRoute: any = { name: childrenFileInfo?.name, path: childrenFileInfo!.path, component: isIndex ? () => import(/* @vite-ignore */ `@/views${childrenFileInfo?.replaceName}`) : undefined, children: [], meta: { isFullScreen: false }, }; // 如果当前路由对象等于当前遍历的路由子对象,将子路由推到父级路由中 if (childrenFileInfo?.path.includes(route.path) && childrenFileInfo?.path !== route.path) { route.children.push(childrenRoute); } }); } /** * 遍历路由信息 * @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(/* @vite-ignore */ fileInfo!.filePath, {}) : undefined, children: [], meta: { isFullScreen: false }, }; // 初始化赋值 if (isIndex) { routeMap[route.path] = route; buildRouteTree(context, isIndex, route); } else { // 导出当前存在的路由并重新赋值 const existingRoute = routeMap[route.path]; // 当前路由存在 if (existingRoute) { // 使用loadsh合并对象 routeMap[route.path] = _.merge(existingRoute, exportRouteConfig); } } }); }; // * 生成路由信息 contexts.forEach(({ context, isIndex }) => createRouteList(context, isIndex)); export const pageRoutes: Array = Object.values(routeMap);