From 0453ce69901dd6c48fa0feb518674c537894d154 Mon Sep 17 00:00:00 2001 From: "hanzebang.hzb" Date: Mon, 15 Apr 2024 13:51:57 +0800 Subject: [PATCH] fix(esbuildHelperChecker): catch js parse error --- .../esbuildHelperChecker.ts | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/packages/preset-umi/src/features/esbuildHelperChecker/esbuildHelperChecker.ts b/packages/preset-umi/src/features/esbuildHelperChecker/esbuildHelperChecker.ts index 21f4673e86ab..5c96da0f29b0 100644 --- a/packages/preset-umi/src/features/esbuildHelperChecker/esbuildHelperChecker.ts +++ b/packages/preset-umi/src/features/esbuildHelperChecker/esbuildHelperChecker.ts @@ -17,6 +17,7 @@ async function checkDir(opts: { dir: string }) { for (const jsFile of jsFiles) { const vars = await getGlobalVars({ content: fs.readFileSync(path.join(opts.dir, jsFile), 'utf-8'), + fileName: jsFile, }); for (const v of vars) { varMap[v] = varMap[v] || []; @@ -40,24 +41,37 @@ async function checkDir(opts: { dir: string }) { logger.info(`[esbuildHelperChecker] No conflicts found.`); } -export async function getGlobalVars(opts: { content: string }) { - const ast = parser.parse(opts.content, { - sourceType: 'module', - sourceFilename: 'foo.js', - plugins: [], - }); +export async function getGlobalVars(opts: { + content: string; + fileName: string; +}) { const vars: string[] = []; - ast.program.body.forEach((node) => { - if (t.isVariableDeclaration(node)) { - node.declarations.forEach((declaration) => { - if (t.isVariableDeclarator(declaration)) { - if (t.isIdentifier(declaration.id)) { - vars.push(declaration.id.name); + /** + * 产物目录可能会有用户自定义的非标准 js 文件,会导致 parse 异常,这里转为 error 提示,不中断程序 + * eg. git lfs 会生成不符合 js 规范的 js 文件 + */ + try { + const ast = parser.parse(opts.content, { + sourceType: 'module', + sourceFilename: 'foo.js', + plugins: [], + }); + ast.program.body.forEach((node) => { + if (t.isVariableDeclaration(node)) { + node.declarations.forEach((declaration) => { + if (t.isVariableDeclarator(declaration)) { + if (t.isIdentifier(declaration.id)) { + vars.push(declaration.id.name); + } } - } - }); - } - }); + }); + } + }); + } catch (error: any) { + logger.error( + `[esbuildHelperChecker] Failed to parse ${opts.fileName}, ${error.message}`, + ); + } return vars; }