You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求可解析的TypeScript文件导入依赖列表的npm命令行工具

解决TypeScript测试依赖自动触发的方案

推荐工具与实操步骤

1. 使用ts-dependency-graph(轻量TS专用工具)

  • 安装:npm install -g ts-dependency-graph
  • 生成单个文件的依赖列表:ts-dependency-graph --entry a.spec.ts --output json
    • 输出为结构化JSON,直接提取dependencies字段就能获取所有被导入的文件路径,无需自行解析复杂输出
  • 批量处理测试文件:可编写简单脚本遍历所有.spec.ts文件,逐个生成依赖并存储为「测试文件→依赖列表」的键值对

2. 自定义脚本结合TypeScript编译器API

若现成工具不符合需求,直接使用TS官方API更精准:

  • 安装依赖:npm install typescript --save-dev
  • 编写Node.js脚本(例如get-test-deps.js):
const ts = require('typescript');
const fs = require('fs');

function getDependencies(filePath) {
  const program = ts.createProgram([filePath], {});
  const sourceFile = program.getSourceFile(filePath);
  const dependencies = new Set();

  function walk(node) {
    if (ts.isImportDeclaration(node)) {
      const moduleSpecifier = node.moduleSpecifier.text;
      // 根据项目tsconfig的路径映射调整解析逻辑
      const resolvedPath = program.resolveModuleName(
        moduleSpecifier,
        sourceFile.fileName,
        {},
        program.getCompilerOptions()
      ).resolvedModule?.resolvedFileName;
      if (resolvedPath) dependencies.add(resolvedPath);
    }
    ts.forEachChild(node, walk);
  }

  walk(sourceFile);
  return Array.from(dependencies);
}

// 示例:处理a.spec.ts
const testFile = './a.spec.ts';
const deps = getDependencies(testFile);
console.log(`${testFile} 的依赖列表:`, deps);
// 将结果写入JSON文件备用
fs.writeFileSync('./test-deps.json', JSON.stringify({ [testFile]: deps }, null, 2));
  • 运行脚本:node get-test-deps.js,输出的依赖为绝对路径,无歧义,便于后续对比文件修改

3. 结合chokidar实现依赖变化自动触发测试

拿到依赖列表后,用文件监听工具关联依赖与测试:

  • 安装:npm install chokidar --save-dev
  • 在脚本中添加监听逻辑:
const chokidar = require('chokidar');

// 读取之前生成的测试依赖映射
const testDeps = require('./test-deps.json');

// 反向构建映射:依赖文件 → 对应的测试文件
const depToTests = {};
Object.entries(testDeps).forEach(([testFile, deps]) => {
  deps.forEach(dep => {
    if (!depToTests[dep]) depToTests[dep] = [];
    depToTests[dep].push(testFile);
  });
});

// 监听所有依赖文件的变化
chokidar.watch(Object.keys(depToTests)).on('change', (changedFile) => {
  const testsToRun = depToTests[changedFile];
  console.log(`文件 ${changedFile} 已修改,需执行测试:`, testsToRun);
  // 这里替换为你的测试命令,例如 `jest ${testsToRun.join(' ')}`
});

关于madge和dependency-tree的问题

  • madge默认解析JS,对TS的路径别名、类型导入支持不足,输出的图形化结构不适合直接提取依赖列表
  • dependency-tree会默认包含node_modules中的依赖,需额外过滤,且对TS模块解析逻辑的匹配度与项目tsconfig差异较大

内容的提问来源于stack exchange,提问作者Jonathan Abrahams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 22:43:11