Files
2nd/10_Wiki/Topics/Architecture/Dependency_Analysis.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

176 lines
5.6 KiB
Markdown

---
id: wiki-2026-0508-dependency-analysis
title: Dependency Analysis
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [dep-analysis, dependency-graph, code-dependency-tools]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [tooling, dependencies, static-analysis]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: javascript
framework: madge/depcheck/knip
---
# Dependency Analysis
## 매 한 줄
> **"매 import graph 가 매 codebase 의 X-ray"**. 매 Madge / dependency-cruiser / Knip / depcheck 가 매 dead code, circular deps, layering violations, unused packages 의 surface. 2026 의 매 Knip + dependency-cruiser + Turbo's prune 가 매 monorepo standard combo.
## 매 핵심
### 매 question types
1. **Module-level**: who imports X? what does X import?
2. **Package-level**: which deps are unused? which are dev-only mislabeled?
3. **Architectural**: 매 cross-layer 의 import 가 있나?
4. **Cycles**: 매 circular dependency.
5. **Reachability**: 매 entry-point 의 reachable X 의 dead code.
### 매 tool matrix
- **Madge** — 매 visualization, circular detection (JS/TS).
- **dependency-cruiser** — 매 rules engine + violations CI.
- **Knip** — 매 unused files/exports/deps (replaces ts-prune + depcheck).
- **depcheck** — 매 unused npm deps (older, Knip 가 better).
- **ts-morph / typescript-eslint** — 매 custom AST analyzer.
- **Nx graph** / **Turborepo prune** — 매 monorepo affected detection.
### 매 응용
1. CI guard — 매 layer violation 시 fail.
2. Dead-code removal — 매 quarterly cleanup.
3. Bundle reduction — 매 unused dep removal → smaller install + lockfile.
4. Refactor planning — 매 high-fan-in module 의 identify.
5. License audit — 매 transitive dep tree.
## 💻 패턴
### Madge 의 circular detection
```bash
npx madge --circular --extensions ts,tsx src/
# 매 circular 가 있으면 fail.
npx madge --image graph.svg src/
# 매 SVG 의 visualization.
```
### dependency-cruiser rules
```js
// .dependency-cruiser.cjs
module.exports = {
forbidden: [
{ name: 'no-circular', severity: 'error', from: {}, to: { circular: true } },
{ name: 'no-orphans', severity: 'warn', from: { orphan: true, pathNot: '\\.test\\.ts$' }, to: {} },
{ name: 'domain-not-import-ui', severity: 'error',
from: { path: '^src/domain' }, to: { path: '^src/ui' } },
{ name: 'no-deprecated-core', severity: 'error',
from: {}, to: { dependencyTypes: ['core'], path: '^(punycode|domain)$' } },
],
options: { tsConfig: { fileName: 'tsconfig.json' } },
};
```
```bash
depcruise --config .dependency-cruiser.cjs src/
```
### Knip (unused exports/files/deps)
```jsonc
// knip.json
{
"entry": ["src/index.ts", "src/cli.ts"],
"project": ["src/**/*.{ts,tsx}"],
"ignoreDependencies": ["husky"]
}
```
```bash
npx knip
# 매 unused files, unused exports, unused deps 의 list.
```
### Turborepo prune (monorepo)
```bash
turbo prune --scope=@acme/web --docker
# 매 web 의 deps 만 가진 minimal package.json 의 emit — Docker layer cache 의 efficient.
```
### Nx affected graph
```bash
npx nx graph
npx nx affected:test --base=main
# 매 변경된 project 의 transitive consumers 만 test.
```
### Custom AST scanner (ts-morph)
```ts
import { Project } from 'ts-morph';
const project = new Project({ tsConfigFilePath: 'tsconfig.json' });
const violations: string[] = [];
for (const sf of project.getSourceFiles()) {
for (const imp of sf.getImportDeclarations()) {
const spec = imp.getModuleSpecifierValue();
if (sf.getFilePath().includes('/domain/') && spec.startsWith('@/ui')) {
violations.push(`${sf.getFilePath()} -> ${spec}`);
}
}
}
if (violations.length) { console.error(violations.join('\n')); process.exit(1); }
```
### Bundle-level (esbuild metafile / vite-bundle-visualizer)
```bash
vite build --emptyOutDir
npx vite-bundle-visualizer
# 매 actual shipped bytes per package — install-time deps 의 differ.
```
### License + SBOM cross-check
```bash
npx license-checker --production --json > licenses.json
npx @cyclonedx/cyclonedx-npm --output-file sbom.json
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Quick circular check | Madge |
| Layer enforcement in CI | dependency-cruiser |
| Unused files/exports/deps | Knip |
| Monorepo affected detection | Turbo / Nx |
| Custom rules | ts-morph script |
| Bundle size (runtime) | vite/esbuild visualizer |
**기본값**: Knip + dependency-cruiser in CI; Madge ad-hoc for visualization; Turbo/Nx in monorepos.
## 🔗 Graph
- 부모: [[Static-Analysis]] · [[Code-Quality]]
- 변형: [[dependency-cruiser]]
- 응용: [[Monorepo]]
- Adjacent: [[SBOM]] · [[Turborepo]]
## 🤖 LLM 활용
**언제**: 매 dependency-cruiser rule synthesis from architecture description, 매 Knip output 의 triage (which 의 truly unused), 매 graph interpretation.
**언제 X**: 매 actual dead-code removal 의 PR (false positive 의 review 필요). 매 production runtime decisions.
## ❌ 안티패턴
- **Run only locally**: 매 CI guard 가 X — 매 violation 의 sneak in.
- **Knip 의 trust blindly**: 매 dynamic require / framework convention 가 false-positive — `ignore` glob 사용.
- **No layer rules**: 매 architecture 가 silently rot.
- **Visualization only**: 매 SVG 가 cool 가, 매 enforcement 가 X.
- **Run on dist/**: 매 source 의 analyze, 매 bundled 의 X.
## 🧪 검증 / 중복
- Verified (Madge docs, dependency-cruiser docs, Knip docs, Turborepo, Nx).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — dependency analysis tools and CI patterns |