From 20353b11b6160ddd17a04fe8320b0110561c5258 Mon Sep 17 00:00:00 2001 From: SoonIter Date: Tue, 15 Oct 2024 14:26:20 +0800 Subject: [PATCH] perf: optimize the resolveConfigPath --- packages/core/src/config.ts | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index d3855029..11aa2bd7 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -70,24 +70,43 @@ export function defineConfig(config: RslibConfigExport) { return config; } -const findConfig = (basePath: string): string | undefined => { - return DEFAULT_CONFIG_EXTENSIONS.map((ext) => basePath + ext).find( - fs.existsSync, +async function isFileExist(filePath: string) { + try { + await fs.promises.access(filePath, fs.constants.R_OK); + return true; + } catch (e) { + return false; + } +} + +const findConfig = async (basePath: string): Promise => { + const promises: Promise[] = DEFAULT_CONFIG_EXTENSIONS.map( + async (ext) => { + const configPath = basePath + ext; + const isExist = await isFileExist(configPath); + return isExist ? configPath : false; + }, ); + const configPaths = await Promise.all(promises); + + return configPaths.find((i) => i !== false); }; -const resolveConfigPath = (root: string, customConfig?: string): string => { +const resolveConfigPath = async ( + root: string, + customConfig?: string, +): Promise => { if (customConfig) { const customConfigPath = isAbsolute(customConfig) ? customConfig : join(root, customConfig); - if (fs.existsSync(customConfigPath)) { + if (await isFileExist(customConfigPath)) { return customConfigPath; } logger.warn(`Cannot find config file: ${color.dim(customConfigPath)}\n`); } - const configFilePath = findConfig(join(root, DEFAULT_CONFIG_NAME)); + const configFilePath = await findConfig(join(root, DEFAULT_CONFIG_NAME)); if (configFilePath) { return configFilePath; @@ -105,7 +124,7 @@ export async function loadConfig({ path?: string; envMode?: string; }): Promise { - const configFilePath = resolveConfigPath(cwd, path); + const configFilePath = await resolveConfigPath(cwd, path); const { content } = await loadRsbuildConfig({ cwd: dirname(configFilePath), path: configFilePath,