Skill站外收录 @skilllib/skill-2014279384188792833
typescript-circular-dependency
提供 TypeScript 和 JavaScript 项目中循环依赖的检测与修复能力,涵盖运行时初始化错误、undefined 导入、类型错误及测试异常等典型场景,支持依赖图谱生成、模式识别和多种重构策略,确保模块初始化顺序正确且类型安全。
效率工具 AI 技能
Skills.MD
# TypeScript Circular Dependency Detection and Resolution
## Problem
Circular dependencies occur when module A imports from module B, which imports
(directly or indirectly) from module A. TypeScript compiles successfully, but at
runtime, one of the imports evaluates to `undefined` because the module hasn't
finished initializing yet.
## Context / Trigger Conditions
Common error messages:
```
ReferenceError: Cannot access 'UserService' before initialization
```
```
TypeError: Cannot read properties of undefined (reading 'create')
```
```
TypeError: (0 , _service.doSomething) is not a function
```
Symptoms that suggest circular imports:
- Import is `undefined` even though the export exists
- Error only appears at runtime, not during TypeScript compilation
- Moving an import statement changes which import is undefined
- Tests fail but the app works (or vice versa)
- Adding `console.log` at the top of a file changes behavior
## Solution
### Step 1: Detect the Cycle
Use a tool to visualize dependencies:
```bash
# Install madge
npm install -g madge
# Find circular dependencies
madge --circular --extensions ts,tsx src/
# Generate visual graph
madge --circular --image graph.svg src/
```
Or use the TypeScript compiler:
```bash
# Check for cycles (requires tsconfig setting)
npx tsc --listFiles | head -50
```
### Step 2: Identify the Pattern
Common circular dependency patterns:
**Pattern A: Service-to-Service**
```
services/userService.ts → services/orderService.ts → services/userService.ts
```
**Pattern B: Type imports**
```
types/user.ts → types/order.ts → types/user.ts
```
**Pattern C: Index barrel files**
```
components/index.ts → components/Button.tsx → components/index.ts
```
### Step 3: Resolution Strategies
**Strategy 1: Extract Shared Dependencies**
Before:
```typescript
// userService.ts
import { OrderService } from './orderService';
export class UserService { ... }
// orderService.ts
import { UserService } from './userService';
export class OrderService { ... }
```
After:
```typescript
// types/interfaces.ts (new file - no imports from services)
export interface IUserService { ... }
export interface IOrderService { ... }
// userService.ts
import { IOrderService } from '../types/interfaces';
export class UserService implements IUserService { ... }
```
**Strategy 2: Dependency Injection**
```typescript
// orderService.ts
export class OrderService {
constructor(private userService: IUserService) {}
// Instead of importing UserService directly
}
// main.ts
const userService = new UserService();
const orderService = new OrderService(userService);
```
**Strategy 3: Dynamic Imports**
```typescript
// Only import when needed, not at module level
async function processOrder() {
const { UserService } = await import('./userService');
// ...
}
```
**Strategy 4: Use Type-Only Imports**
If you only need types (not values), use type-only imports:
```typescript
// This doesn't create a runtime dependency
import type { User } from './userService';
```
**Strategy 5: Restructure Barrel Files**
Before (problematic):
```typescript
// components/index.ts
export * from './Button';
export * from './Modal'; // Modal imports Button from './index'
```
After:
```typescript
// components/Modal.tsx
import { Button } from './Button'; // Direct import, not from index
```
### Step 4: Prevent Future Cycles
Add to your CI/build process:
```json
// package.json
{
"scripts": {
"check:circular": "madge --circular --extensions ts,tsx src/"
}
}
```
Or configure ESLint:
```javascript
// .eslintrc.js
module.exports = {
plugins: ['import'],
rules: {
'import/no-cycle': ['error', { maxDepth: 10 }]
}
}
```
## Verification
1. Run `madge --circular src/` - should report no cycles
2. Run your test suite - previously undefined imports should work
3. Delete `node_modules` and reinstall - app should still work
4. Build for production - no runtime errors
## Example
**Problem**: `OrderService` is undefined when imported in `UserService`
**Detection**:
```bash
$ madge --circular src/
Circular dependencies found!
src/services/userService.ts → src/services/orderService.ts → src/services/userService.ts
```
**Fix**: Extract shared interface
```typescript
// NEW: src/types/services.ts
export interface IOrderService {
createOrder(userId: string): Promise<Order>;
}
// MODIFIED: src/services/userService.ts
import type { IOrderService } from '../types/services';
export class UserService {
constructor(private orderService: IOrderService) {}
}
// MODIFIED: src/services/orderService.ts
// No longer imports UserService
export class OrderService implements IOrderService {
async createOrder(userId: string): Promise<Order> { ... }
}
```
## Notes
- TypeScript `import type` is your friend—it's erased at runtime and can't cause cycles
- Barrel files (`index.ts`) are a common source of accidental cycles
- The order of exports in a file can matter when there's a cycle
- Jest/Vitest may handle module resolution differently than your bundler
- Some bundlers (Webpack, Vite) have better cycle handling than others
- `require()` can sometimes mask circular dependency issues that `import` exposes
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「typescript-circular-dependency」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次