Introduction
Madge creates dependency graphs from JavaScript, TypeScript, and CSS source files. It parses import and require statements to build a module tree, then renders it as a visual diagram or reports circular dependencies that can cause subtle bugs.
What Madge Does
- Parses CommonJS, AMD, and ES6 module imports to build a dependency tree
- Detects circular dependencies and reports the exact import chains involved
- Generates visual graphs in SVG, PNG, PDF, or DOT format using Graphviz
- Supports JavaScript, TypeScript, JSX, TSX, and CSS/SASS/LESS files
- Works with webpack and TypeScript path aliases via configuration
Architecture Overview
Madge uses a combination of detective-based AST parsing (precinct) and the TypeScript compiler API to resolve imports across your project. It builds an adjacency list of module relationships, runs cycle detection via depth-first search, and pipes the graph to Graphviz (dot) for rendering when visual output is requested.
Self-Hosting & Configuration
- Install globally or as a dev dependency: npm install madge --save-dev
- Install Graphviz separately for image output: brew install graphviz or apt install graphviz
- Configure via .madgerc in your project root or pass a JSON config file
- Map path aliases with webpackConfig or tsConfig options to resolve non-relative imports
- Set fileExtensions to include or exclude specific file types
Key Features
- Circular dependency detection with full cycle path reporting
- Multiple output formats: JSON tree, text list, DOT graph, or rendered image
- TypeScript and path alias support out of the box with tsconfig resolution
- Exclude patterns to skip node_modules, test files, or generated code
- Programmatic API for integration into build pipelines and CI checks
Comparison with Similar Tools
- dependency-cruiser — More rule-based with policy enforcement; Madge focuses on visualization and circular detection
- Webpack Bundle Analyzer — Analyzes bundle size, not module relationships; Madge maps import structure
- nx graph — Monorepo-level project dependencies; Madge works at the file/module level within a single project
- ESLint import/no-cycle — Lint rule that catches cycles one file at a time; Madge reports all cycles project-wide in one pass
FAQ
Q: Does Madge require Graphviz? A: Only for image output. JSON, text, and DOT output work without Graphviz. Install Graphviz when you need SVG/PNG rendering.
Q: Can Madge handle TypeScript path aliases? A: Yes. Point Madge to your tsconfig.json with the --ts-config flag and it resolves paths automatically.
Q: How do I integrate Madge into CI? A: Run madge --circular src/ in your CI pipeline. It exits with code 1 when circular dependencies are found, failing the build.
Q: Does it support monorepos? A: Madge works per-directory. Point it at a specific package's source folder and it analyzes that subtree. For cross-package graphs, consider dependency-cruiser.