0
# Programmatic API
1
2
Core programmatic interface for dependency analysis and graph generation. Perfect for integrating into build tools, CI pipelines, and custom workflows.
3
4
## Capabilities
5
6
### Main Function
7
8
Creates a new Madge instance for analyzing module dependencies.
9
10
```javascript { .api }
11
/**
12
* Analyze module dependencies for the given path(s)
13
* @param path - Single file path, array of paths, or predefined dependency tree object
14
* @param config - Optional configuration object
15
* @returns Promise resolving to Madge instance
16
*/
17
function madge(path: string | string[] | object, config?: MadgeConfig): Promise<MadgeInstance>;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const madge = require('madge');
24
25
// Analyze single file
26
const res = await madge('src/app.js');
27
28
// Analyze multiple files
29
const res = await madge(['src/app.js', 'src/utils.js']);
30
31
// Analyze directory
32
const res = await madge('src/');
33
34
// Use predefined tree
35
const tree = { 'a.js': ['b.js'], 'b.js': [] };
36
const res = await madge(tree);
37
38
// With configuration
39
const res = await madge('src/', {
40
excludeRegExp: ['node_modules'],
41
fileExtensions: ['js', 'jsx', 'ts', 'tsx'],
42
includeNpm: false,
43
detectiveOptions: {
44
es6: { mixedImports: true },
45
ts: { skipTypeImports: true }
46
}
47
});
48
```
49
50
### Dependency Tree Access
51
52
Get the raw dependency tree as an object.
53
54
```javascript { .api }
55
/**
56
* Return the module dependency graph as an object
57
* @returns Object with module paths as keys and dependency arrays as values
58
*/
59
obj(): object;
60
```
61
62
**Usage Example:**
63
64
```javascript
65
const res = await madge('src/');
66
const tree = res.obj();
67
console.log(tree);
68
// {
69
// 'src/app.js': ['src/utils.js', 'src/api.js'],
70
// 'src/utils.js': [],
71
// 'src/api.js': ['src/config.js']
72
// }
73
```
74
75
### Warnings Access
76
77
Get warnings about skipped files during analysis.
78
79
```javascript { .api }
80
/**
81
* Return produced warnings including skipped files
82
* @returns Object containing warning information
83
*/
84
warnings(): object;
85
```
86
87
**Usage Example:**
88
89
```javascript
90
const res = await madge('src/');
91
const warnings = res.warnings();
92
console.log(warnings.skipped); // Array of file paths that were skipped
93
```
94
95
### Circular Dependencies
96
97
Find modules with circular dependencies.
98
99
```javascript { .api }
100
/**
101
* Return the modules that have circular dependencies
102
* @returns Array of circular dependency chains
103
*/
104
circular(): string[];
105
```
106
107
**Usage Example:**
108
109
```javascript
110
const res = await madge('src/');
111
const circular = res.circular();
112
console.log(circular);
113
// [['a.js', 'b.js', 'a.js'], ['c.js', 'd.js', 'e.js', 'c.js']]
114
```
115
116
### Circular Dependency Graph
117
118
Get dependency graph containing only circular dependencies.
119
120
```javascript { .api }
121
/**
122
* Return circular dependency graph containing only circular dependencies
123
* @returns Object with only modules involved in circular dependencies
124
*/
125
circularGraph(): object;
126
```
127
128
### Module Dependents
129
130
Find all modules that depend on a specific module.
131
132
```javascript { .api }
133
/**
134
* Return a list of modules that depend on the given module
135
* @param id - Module identifier to find dependents for
136
* @returns Array of module paths that depend on the specified module
137
*/
138
depends(id: string): string[];
139
```
140
141
**Usage Example:**
142
143
```javascript
144
const res = await madge('src/');
145
const dependents = res.depends('src/utils.js');
146
console.log(dependents); // ['src/app.js', 'src/api.js']
147
```
148
149
### Orphan Modules
150
151
Find modules that no other modules depend on.
152
153
```javascript { .api }
154
/**
155
* Return a list of modules that no one is depending on
156
* @returns Array of module paths that are not imported by any other module
157
*/
158
orphans(): string[];
159
```
160
161
**Usage Example:**
162
163
```javascript
164
const res = await madge('src/');
165
const orphans = res.orphans();
166
console.log(orphans); // ['src/unused.js', 'src/legacy.js']
167
```
168
169
### Leaf Modules
170
171
Find modules that have no dependencies.
172
173
```javascript { .api }
174
/**
175
* Return a list of modules that have no dependencies
176
* @returns Array of module paths that don't import any other modules
177
*/
178
leaves(): string[];
179
```
180
181
### DOT Graph Generation
182
183
Generate DOT format representation of the dependency graph.
184
185
```javascript { .api }
186
/**
187
* Return the module dependency graph as DOT output
188
* @param circularOnly - If true, only include circular dependencies
189
* @returns Promise resolving to DOT format string
190
*/
191
dot(circularOnly?: boolean): Promise<string>;
192
```
193
194
**Usage Example:**
195
196
```javascript
197
const res = await madge('src/');
198
const dotOutput = await res.dot();
199
console.log(dotOutput); // digraph G { ... }
200
201
// Only circular dependencies
202
const circularDot = await res.dot(true);
203
```
204
205
### Image Generation
206
207
Generate visual graph as image file.
208
209
```javascript { .api }
210
/**
211
* Write dependency graph to image file
212
* @param imagePath - Path where image should be written
213
* @param circularOnly - If true, only include circular dependencies
214
* @returns Promise resolving to the written image path
215
*/
216
image(imagePath: string, circularOnly?: boolean): Promise<string>;
217
```
218
219
**Usage Example:**
220
221
```javascript
222
const res = await madge('src/');
223
const imagePath = await res.image('graph.svg');
224
console.log('Graph written to:', imagePath);
225
226
// Only circular dependencies
227
await res.image('circular.svg', true);
228
```
229
230
**Note:** Requires Graphviz to be installed on the system.
231
232
### SVG Generation
233
234
Generate SVG representation as Buffer.
235
236
```javascript { .api }
237
/**
238
* Return Buffer with XML SVG representation of the dependency graph
239
* @returns Promise resolving to SVG Buffer
240
*/
241
svg(): Promise<Buffer>;
242
```
243
244
**Usage Example:**
245
246
```javascript
247
const res = await madge('src/');
248
const svgBuffer = await res.svg();
249
const svgString = svgBuffer.toString();
250
console.log(svgString); // SVG XML content
251
```
252
253
## Configuration
254
255
```javascript { .api }
256
interface MadgeConfig {
257
/** Base directory to use instead of the default */
258
baseDir?: string;
259
/** If shallow NPM modules should be included */
260
includeNpm?: boolean;
261
/** Valid file extensions used to find files in directories */
262
fileExtensions?: string[];
263
/** An array of RegExp for excluding modules */
264
excludeRegExp?: string[] | false;
265
/** RequireJS config for resolving aliased modules */
266
requireConfig?: string;
267
/** Webpack config for resolving aliased modules */
268
webpackConfig?: string;
269
/** TypeScript config for resolving aliased modules */
270
tsConfig?: string | object;
271
/** Layout to use in the graph */
272
layout?: string;
273
/** Sets the direction of the graph layout */
274
rankdir?: string;
275
/** Font name to use in the graph */
276
fontName?: string;
277
/** Font size to use in the graph */
278
fontSize?: string;
279
/** Background color for the graph */
280
backgroundColor?: string;
281
/** A string specifying the shape of a node in the graph */
282
nodeShape?: string;
283
/** A string specifying the style of a node in the graph */
284
nodeStyle?: string;
285
/** Default node color to use in the graph */
286
nodeColor?: string;
287
/** Color to use for nodes with no dependencies */
288
noDependencyColor?: string;
289
/** Color to use for circular dependencies */
290
cyclicNodeColor?: string;
291
/** Edge color to use in the graph */
292
edgeColor?: string;
293
/** Custom Graphviz options */
294
graphVizOptions?: object | false;
295
/** Custom Graphviz path */
296
graphVizPath?: string | false;
297
/** Custom detective options for dependency-tree and precinct */
298
detectiveOptions?: DetectiveOptions | false;
299
/** Function called with a dependency filepath (exclude subtrees by returning false) */
300
dependencyFilter?: Function | false;
301
}
302
303
interface DetectiveOptions {
304
/** ES6 module detection options */
305
es6?: {
306
/** Enable mixed import/require syntax detection */
307
mixedImports?: boolean;
308
/** Skip import type statements in Flow/TypeScript */
309
skipTypeImports?: boolean;
310
};
311
/** TypeScript module detection options */
312
ts?: {
313
/** Enable mixed import/require syntax detection */
314
mixedImports?: boolean;
315
/** Skip import type statements */
316
skipTypeImports?: boolean;
317
/** Skip dynamic import() statements */
318
skipAsyncImports?: boolean;
319
};
320
/** TSX module detection options */
321
tsx?: {
322
/** Skip dynamic import() statements */
323
skipAsyncImports?: boolean;
324
};
325
}
326
```
327
328
## Error Handling
329
330
Common errors that may be thrown:
331
332
- **Path not provided**: Constructor throws Error if path argument is missing
333
- **Image path not provided**: `image()` method rejects Promise if imagePath is missing
334
- **Graphviz not installed**: Graph generation methods (`.image()`, `.svg()`, `.dot()`) may throw Error if Graphviz is not found when required
335
- **File access errors**: May throw filesystem errors if files cannot be read or accessed
336
- **Invalid configuration**: TypeScript config parsing errors if tsConfig path is invalid
337
- **JSON parsing errors**: When using predefined tree object, invalid JSON structure may cause parsing errors
338
- **Dependency resolution errors**: Files that cannot be parsed or have invalid syntax may cause dependency tree generation to fail
339
340
**Usage Example:**
341
342
```javascript
343
try {
344
const res = await madge('src/');
345
console.log(res.obj());
346
} catch (error) {
347
if (error.message.includes('path argument not provided')) {
348
console.error('Please provide a valid path');
349
} else if (error.code === 'ENOENT') {
350
console.error('File or directory not found');
351
} else {
352
console.error('Analysis failed:', error.message);
353
}
354
}
355
```