utils/autoRouteHelper.ts
// src/utils/autoRouteHelper.ts
import { lazy } from "react";
import withLoading from "@/components/router/withLoading";/** 自動生成某個文件夾下的子路由 */
interface RouteItem {path: string;element?: any;children?: RouteItem[];handle?: {title: string;};
}/*** 生成嵌套路由樹(保留 children 樹結構,排除 components)* @param globModules 模塊對象* @param baseDir 模塊路徑* @param titleMap 路由標題映射表* @returns 返回樹形結構路由數據*/
export function generateNestedRoutes(globModules: Record<string, () => Promise<any>>,baseDir: string,titleMap: Record<string, string> = {}
): RouteItem[] {const root: Record<string, any> = {};for (const [fullPath, loader] of Object.entries(globModules)) {if (fullPath.includes("/components/")) continue;const reg = new RegExp(`${baseDir}/(.*)/index\\.tsx$`, "i");const match = fullPath.match(reg);if (!match) continue;const subPath = match[1].replace(/\\/g, "/"); // windows 兼容const segments = subPath.split("/"); // ["pageb", "list"]let current = root;// let fullSegmentPath = "";for (let i = 0; i < segments.length; i++) {const segment = segments[i];// fullSegmentPath += (i === 0 ? "" : "/") + segment;if (!current[segment]) {current[segment] = {path: segment,childrenMap: {}};}// 最后一層,掛 element 和 titleif (i === segments.length - 1) {current[segment].element = withLoading(lazy(loader));current[segment].handle = {title: titleMap[subPath.toLowerCase()] || segment};}current = current[segment].childrenMap;}}// 將 childrenMap 轉為 children[]function convertToTree(obj: Record<string, any>): RouteItem[] {return Object.values(obj).map(({ childrenMap, ...rest }) => {const node: RouteItem = { ...rest };const children = convertToTree(childrenMap);if (children.length > 0) node.children = children;return node;});}return convertToTree(root);
}/** 合并所有模塊的默認導出,適合用于路由模塊化(eager 模式) */
export function mergeModuleRoutes(modules: Record<string, any>
): any[] {const routes: any[] = [];Object.values(modules).forEach((mod: any) => {if (Array.isArray(mod.default)) {routes.push(...mod.default);} else if (mod.default) {routes.push(mod.default);}});return routes;
}
react路由使用
目錄\router\modules\supplier.ts
import.meta.glob(‘@/pages/supplier/**/index.tsx’); 自動獲取pages/supplier目錄下的所有頁面傳遞給generateNestedRoutes返回路由不限制層級,可以一二級也可以一二三四級別等等
\router\modules
新增路由文件 如supplier.ts
import { lazy } from "react";
import withLoading from "@/components/router/withLoading";
import { generateNestedRoutes } from "@/utils/routerHelper";const personalPageModules = import.meta.glob('@/pages/supplier/**/index.tsx');const titleMap: Record<string, string> = {list: "供應商列表",// 你可以繼續添加其他路徑對應的標題
};/** 供應商管理 */
const supplier: Array<any> = [{path: "supplier",element: withLoading(lazy(() => import("@/pages/supplier/index"))),handle: {title: "供應商管理",},children:[...generateNestedRoutes(personalPageModules,"supplier",titleMap)]},
];
console.log(supplier,"供應商管理")
export default supplier;router/index.ts目錄中
const modules = import.meta.glob('./modules/*.ts', { eager: true });...mergeModuleRoutes(modules),
自動獲取modules目錄下的所有路由文件
vue路由中使用
routerHelper.ts
// src/utils/autoRouteHelper.ts
// src/utils/autoRouteHelper.ts
/*** 自動生成某個模塊文件夾下的子路由(用于 Vue Router)*/interface TitleMap {[key: string]: string;
}interface AutoRouteOptions {/** 模塊目錄,如 'views/merchantmanage' */baseDir: string;/** 路由標題映射表 */titleMap?: TitleMap;/** 排除目錄數組,如 ['components', 'common'] */excludeDirs?: string[];
}/*** 自動生成某個目錄下的子路由,支持多級目錄,支持排除子目錄* @param globModules import.meta.glob 的結果* @param options 配置項*/
export function generateChildrenRoutes(globModules: Record<string, () => Promise<any>>,options: AutoRouteOptions
) {const { baseDir, titleMap = {}, excludeDirs = [] } = options;return Object.entries(globModules).map(([fullPath, loader]) => {// 1. 判斷是否命中排除目錄const shouldExclude = excludeDirs.some((dir) =>fullPath.includes(`${baseDir}/${dir}/`));if (shouldExclude) return null;// 2. 提取 baseDir 后的子路徑部分const match = fullPath.match(new RegExp(`${baseDir}/(.+)\\.vue$`));if (!match) return null;const subPath = match[1]; // 例:user/detail/index 或 homeconst segments = subPath.split('/');// 構建路由 path,忽略 indexlet routePath = segments.map((seg) => (seg === 'index' ? '' : seg)).filter(Boolean).join('/');if (!routePath) routePath = '';const routeName = routePath.replace(/\//g, '-');return {path: routePath,name: routeName,component: loader,meta: {title: titleMap[routePath.toLowerCase()] || segments.at(-1) || routePath}};}).filter(Boolean) as any[];
}/** 合并所有模塊的默認導出,適合用于路由模塊化(eager 模式) */
export function mergeModuleRoutes(modules: Record<string, any>
): any[] {const routes: any[] = [];Object.values(modules).forEach((mod: any) => {if (Array.isArray(mod.default)) {routes.push(...mod.default);} else if (mod.default) {routes.push(mod.default);}});return routes;
}
/使用實例
const modules = import.meta.glob('@/views/merchantmanage/**/*.vue');const routes = generateChildrenRoutes(modules, {baseDir: 'views/merchantmanage',excludeDirs: ['components', 'fragments', 'common'],titleMap: {user: '用戶管理','user/detail': '用戶詳情'}
});