From 919a73680df33cd160e2d8218e574b6254c0c7a9 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 16 Jul 2024 19:29:44 +0800 Subject: [PATCH] refactor: getConventionRoutes --- packages/core/src/route/routesConvention.ts | 26 +++++++++++++-------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/core/src/route/routesConvention.ts b/packages/core/src/route/routesConvention.ts index 763eb35cc562..5d549c64eb51 100644 --- a/packages/core/src/route/routesConvention.ts +++ b/packages/core/src/route/routesConvention.ts @@ -2,12 +2,7 @@ import { winPath } from '@umijs/utils'; import { existsSync, lstatSync, readdirSync, statSync } from 'fs'; import { extname, relative, resolve } from 'path'; import { defineRoutes } from './defineRoutes'; -import { - byLongestFirst, - createRouteId, - findParentRouteId, - isRouteModuleFile, -} from './utils'; +import { byLongestFirst, createRouteId, isRouteModuleFile } from './utils'; // opts.base: path of pages export function getConventionRoutes(opts: { @@ -30,11 +25,22 @@ export function getConventionRoutes(opts: { }); const routeIds = Object.keys(files).sort(byLongestFirst); - + const parentToChildrenMap = new Map(); + routeIds.forEach((id) => { + const prefix = `${id}/`; + routeIds + .filter((childId) => childId.startsWith(prefix) && childId !== id) + .forEach((childId) => { + if (!parentToChildrenMap.has(id)) { + parentToChildrenMap.set(id, []); + } + parentToChildrenMap.get(id).push(childId); + }); + }); function defineNestedRoutes(defineRoute: any, parentId?: string) { - const childRouteIds = routeIds.filter( - (id) => findParentRouteId(routeIds, id) === parentId, - ); + const childRouteIds = parentId + ? parentToChildrenMap.get(parentId) + : routeIds; for (let routeId of childRouteIds) { let routePath = createRoutePath( parentId ? routeId.slice(parentId.length + 1) : routeId,