vite_ts_auto/src/router/module/pageRoutes.ts

77 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-05-08 13:43:24 +08:00
import { routeFilenameHelper } from '@/utils/file/routeFileUtil';
2024-05-09 14:55:40 +08:00
import _ from 'lodash';
2024-05-08 13:43:24 +08:00
import { RouteRecordRaw } from 'vue-router';
// * 最终路由
const routeMap: Record<string, RouteRecordRaw> = {};
// * 所有处理的路由
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 },
2024-05-08 13:43:24 +08:00
];
2024-05-09 14:55:40 +08:00
/**
*
* @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);
}
});
}
2024-05-08 13:43:24 +08:00
/**
*
* @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,
2024-05-09 14:55:40 +08:00
children: [],
meta: { isFullScreen: false },
2024-05-08 13:43:24 +08:00
};
2024-05-09 14:55:40 +08:00
2024-05-08 13:43:24 +08:00
// 初始化赋值
if (isIndex) {
routeMap[route.path] = route;
2024-05-09 14:55:40 +08:00
buildRouteTree(context, isIndex, route);
} else {
2024-05-08 13:43:24 +08:00
// 导出当前存在的路由并重新赋值
const existingRoute = routeMap[route.path];
2024-05-09 14:55:40 +08:00
// 当前路由存在
2024-05-08 13:43:24 +08:00
if (existingRoute) {
2024-05-09 14:55:40 +08:00
// 使用loadsh合并对象
routeMap[route.path] = _.merge(existingRoute, exportRouteConfig);
2024-05-08 13:43:24 +08:00
}
}
});
2024-05-08 13:43:24 +08:00
};
// * 生成路由信息
contexts.forEach(({ context, isIndex }) => createRouteList(context, isIndex));
2024-05-08 13:43:24 +08:00
2024-05-09 14:55:40 +08:00
export const pageRoutes: Array<RouteRecordRaw> = Object.values(routeMap);