From d763185fb67e33f0d74f02cd8f31a6a1696dfb08 Mon Sep 17 00:00:00 2001 From: zhf <1204297681@qq.com> Date: Fri, 23 May 2025 22:45:23 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Ddts=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E4=BE=9D=E8=B5=96=E6=8A=A5=E9=94=99=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/src/generate-dts/generate-dts.ts | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/packages/core/src/generate-dts/generate-dts.ts b/packages/core/src/generate-dts/generate-dts.ts index cbd8015..e365520 100644 --- a/packages/core/src/generate-dts/generate-dts.ts +++ b/packages/core/src/generate-dts/generate-dts.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-constant-condition */ import { execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; @@ -121,6 +122,27 @@ const copyFolderRecursive = (source: string, target: string): void => { }); }; +/** + * @description 获取项目package.json路径 + * @param {string} startPath + * @returns {*} {(string | undefined)} + */ +const findProjectPackageJson = (startPath: string): string | undefined => { + let currentPath = path.resolve(startPath); + while (true) { + const packageJsonPath = path.join(currentPath, 'package.json'); + if (fs.existsSync(packageJsonPath)) { + return packageJsonPath; + } + const parentPath = path.dirname(currentPath); + // 若已到达根目录,停止查找 + if (parentPath === currentPath) { + return; + } + currentPath = parentPath; + } +}; + /** * @description 生成dts文件 * @export @@ -174,14 +196,19 @@ export async function generateDts(configPath: string): Promise { }); // 获取依赖信息 - const output = execSync('npm list --depth=0 --json', { - cwd: dir, - }).toString(); - const dependenciesData = JSON.parse(output); - const dependencies = dependenciesData.dependencies; + const packageJsonPath = findProjectPackageJson(dir); + if (!packageJsonPath) { + return; + } + const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8'); + const packageJson = JSON.parse(packageJsonContent); + const dependencies = packageJson.dependencies; + const devDependencies = packageJson.devDependencies; allExternalImports.forEach(importPath => { - if (dependencies[importPath]) { - referencedDependencies[importPath] = dependencies[importPath].version; + if (dependencies && dependencies[importPath]) { + referencedDependencies[importPath] = dependencies[importPath]; + } else if (devDependencies && devDependencies[importPath]) { + referencedDependencies[importPath] = devDependencies[importPath]; } }); }); -- Gitee