From d63da9eae4bb673c5d7f6f9b59b67ea26d5cbf12 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Thu, 18 Jul 2024 13:49:34 +0800 Subject: [PATCH] refactor: getConventionRoutes (#12576) * refactor: getConventionRoutes * fix: iter() * chore: delete core utils findParentRouteId --- packages/core/src/route/routesConvention.ts | 26 +++++++++++++-------- packages/core/src/route/utils.ts | 7 ------ 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/packages/core/src/route/routesConvention.ts b/packages/core/src/route/routesConvention.ts index 763eb35cc562..2b6fc5edff5c 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, diff --git a/packages/core/src/route/utils.ts b/packages/core/src/route/utils.ts index 6c192c9c2bd5..210f77a71d39 100644 --- a/packages/core/src/route/utils.ts +++ b/packages/core/src/route/utils.ts @@ -13,13 +13,6 @@ export function byLongestFirst(a: string, b: string): number { return b.length - a.length; } -export function findParentRouteId( - routeIds: string[], - childRouteId: string, -): string | undefined { - return routeIds.find((id) => childRouteId.startsWith(`${id}/`)); -} - const routeModuleExts = ['.js', '.jsx', '.ts', '.tsx', '.md', '.mdx', '.vue']; export function isRouteModuleFile(opts: { file: string; exclude?: RegExp[] }) { // TODO: add cache strategy