SuperAPI AI 工具集

typescript-circular-dependency

编程与开发

查看项目

更新于 10-15 20:06

技能介绍

用途:检测并解决 TypeScript/JavaScript 模块间的循环导入依赖。循环依赖指模块 A 导入 B、B 又直接或间接导入 A,TypeScript 能编译通过,但运行时某个导入会因模块尚未初始化完成而变成 undefined。

触发场景:常见报错包括 ReferenceError: Cannot access 'UserService' before initialization、TypeError: Cannot read properties of undefined、TypeError: (0 , _service.doSomething) is not a function。典型症状是导出存在但导入为 undefined、错误只在运行时出现、移动 import 语句会改变哪个导入为 undefined、测试与应用表现不一致、在文件顶部加 console.log 会改变行为。

主要能力与用法:

  1. 检测循环。可用 madge:npm install -g madge;madge --circular --extensions ts,tsx src/;madge --circular --image graph.svg src/。也可用 npx tsc --listFiles | head -50 辅助查看。
  2. 识别模式,如服务间互引、类型文件互引、index 桶文件互引。
  3. 解决策略:抽取共享依赖到独立接口文件;使用依赖注入;改用动态 import;仅需类型时使用 import type;重构桶文件为直接导入。
  4. 预防:在 package.json 加 "check:circular": "madge --circular --extensions ts,tsx src/",或配置 ESLint 的 import/no-cycle 规则。

验证:运行 madge --circular src/ 应无循环;运行测试套件;删除 node_modules 重装后仍正常;生产构建无运行时错误。

限制与注意:import type 在运行时被擦除,不会造成循环;桶文件是常见循环来源;导出顺序在存在循环时可能影响结果;Jest/Vitest 与打包器的模块解析可能不同;不同打包器对循环的处理能力不一;require() 有时会掩盖 import 暴露的循环问题。具体平台与收费信息暂未提供。