如何获取TS文件中所有独立导入项的绝对路径列表?
解析TS/TSX文件导入项与对应绝对路径的方案
依赖准备
先安装TypeScript,我们用它的Compiler API来处理文件解析和路径映射:
npm install typescript --save-dev
编写解析脚本
创建parse-imports.ts脚本,代码如下:
import * as ts from 'typescript'; import * as path from 'path'; // 匹配项目的TS配置,重点配置别名映射 const compilerOptions: ts.CompilerOptions = { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.CommonJS, baseUrl: './', // 替换为你的项目根目录 paths: { 'src/*': ['src/*'] // 对应webpack的别名规则,按需修改 } }; // 解析导入路径为绝对路径 const resolveImportPath = (importPath: string, sourceFile: ts.SourceFile) => { const resolved = ts.resolveModuleName(importPath, sourceFile.fileName, compilerOptions, ts.sys); return resolved.resolvedModule?.resolvedFileName || importPath; }; // 解析单个文件的所有导入项 const parseSingleFileImports = (filePath: string) => { const program = ts.createProgram([filePath], compilerOptions); const sourceFile = program.getSourceFile(filePath)!; const importsList: Array<{ name: string; path: string }> = []; ts.forEachChild(sourceFile, node => { if (!ts.isImportDeclaration(node)) return; const modulePath = node.moduleSpecifier.getText().replace(/['"]/g, ''); const absolutePath = resolveImportPath(modulePath, sourceFile); // 处理默认导入 if (node.importClause?.name) { importsList.push({ name: node.importClause.name.getText(), path: absolutePath }); } // 处理命名导入 if (node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)) { node.importClause.namedBindings.elements.forEach(el => { importsList.push({ name: el.name.getText(), path: absolutePath }); }); } }); return importsList; }; // 递归解析文件及所有依赖的导入项 const parseRecursiveImports = (filePath: string, processed = new Set<string>()) => { const absPath = path.resolve(filePath); if (processed.has(absPath)) return []; processed.add(absPath); const currentImports = parseSingleFileImports(absPath); // 递归处理导入的文件 for (const item of currentImports) { const ext = path.extname(item.path); if ([ '.ts', '.tsx', '.js', '.jsx' ].includes(ext)) { currentImports.push(...parseRecursiveImports(item.path, processed)); } } return currentImports; }; // 执行解析并输出结果 const targetFile = path.resolve('./a.tsx'); // 替换为你的目标文件路径 const result = parseRecursiveImports(targetFile); result.forEach(item => { console.log(`- ${item.name} - ${item.path}`); });
运行脚本
用ts-node直接运行脚本:
npx ts-node parse-imports.ts
关键说明
- 脚本通过TypeScript Compiler API解析文件,能自动处理相对路径和tsconfig配置的别名(对应webpack的别名规则),输出每个导入项的名称和绝对路径。
- 支持递归解析所有依赖文件的导入项,若不需要递归,直接调用
parseSingleFileImports方法即可。 - 要确保
compilerOptions里的baseUrl和paths与项目实际配置一致,否则别名解析会出错。
内容的提问来源于stack exchange,提问作者Aakash Verma
相关产品推荐
相关产品推荐

