diff --git a/packages/core/src/generate-dts/generate-dts.ts b/packages/core/src/generate-dts/generate-dts.ts index cbd801580285732e465165a4f3050162ecff6fc4..e3655208b16ff5729e72a03441bdebd425a78829 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]; } }); });