Create graphs from module dependencies.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core programmatic interface for dependency analysis and graph generation. Perfect for integrating into build tools, CI pipelines, and custom workflows.
Creates a new Madge instance for analyzing module dependencies.
/**
* Analyze module dependencies for the given path(s)
* @param path - Single file path, array of paths, or predefined dependency tree object
* @param config - Optional configuration object
* @returns Promise resolving to Madge instance
*/
function madge(path: string | string[] | object, config?: MadgeConfig): Promise<MadgeInstance>;Usage Examples:
const madge = require('madge');
// Analyze single file
const res = await madge('src/app.js');
// Analyze multiple files
const res = await madge(['src/app.js', 'src/utils.js']);
// Analyze directory
const res = await madge('src/');
// Use predefined tree
const tree = { 'a.js': ['b.js'], 'b.js': [] };
const res = await madge(tree);
// With configuration
const res = await madge('src/', {
excludeRegExp: ['node_modules'],
fileExtensions: ['js', 'jsx', 'ts', 'tsx'],
includeNpm: false,
detectiveOptions: {
es6: { mixedImports: true },
ts: { skipTypeImports: true }
}
});Get the raw dependency tree as an object.
/**
* Return the module dependency graph as an object
* @returns Object with module paths as keys and dependency arrays as values
*/
obj(): object;Usage Example:
const res = await madge('src/');
const tree = res.obj();
console.log(tree);
// {
// 'src/app.js': ['src/utils.js', 'src/api.js'],
// 'src/utils.js': [],
// 'src/api.js': ['src/config.js']
// }Get warnings about skipped files during analysis.
/**
* Return produced warnings including skipped files
* @returns Object containing warning information
*/
warnings(): object;Usage Example:
const res = await madge('src/');
const warnings = res.warnings();
console.log(warnings.skipped); // Array of file paths that were skippedFind modules with circular dependencies.
/**
* Return the modules that have circular dependencies
* @returns Array of circular dependency chains
*/
circular(): string[];Usage Example:
const res = await madge('src/');
const circular = res.circular();
console.log(circular);
// [['a.js', 'b.js', 'a.js'], ['c.js', 'd.js', 'e.js', 'c.js']]Get dependency graph containing only circular dependencies.
/**
* Return circular dependency graph containing only circular dependencies
* @returns Object with only modules involved in circular dependencies
*/
circularGraph(): object;Find all modules that depend on a specific module.
/**
* Return a list of modules that depend on the given module
* @param id - Module identifier to find dependents for
* @returns Array of module paths that depend on the specified module
*/
depends(id: string): string[];Usage Example:
const res = await madge('src/');
const dependents = res.depends('src/utils.js');
console.log(dependents); // ['src/app.js', 'src/api.js']Find modules that no other modules depend on.
/**
* Return a list of modules that no one is depending on
* @returns Array of module paths that are not imported by any other module
*/
orphans(): string[];Usage Example:
const res = await madge('src/');
const orphans = res.orphans();
console.log(orphans); // ['src/unused.js', 'src/legacy.js']Find modules that have no dependencies.
/**
* Return a list of modules that have no dependencies
* @returns Array of module paths that don't import any other modules
*/
leaves(): string[];Generate DOT format representation of the dependency graph.
/**
* Return the module dependency graph as DOT output
* @param circularOnly - If true, only include circular dependencies
* @returns Promise resolving to DOT format string
*/
dot(circularOnly?: boolean): Promise<string>;Usage Example:
const res = await madge('src/');
const dotOutput = await res.dot();
console.log(dotOutput); // digraph G { ... }
// Only circular dependencies
const circularDot = await res.dot(true);Generate visual graph as image file.
/**
* Write dependency graph to image file
* @param imagePath - Path where image should be written
* @param circularOnly - If true, only include circular dependencies
* @returns Promise resolving to the written image path
*/
image(imagePath: string, circularOnly?: boolean): Promise<string>;Usage Example:
const res = await madge('src/');
const imagePath = await res.image('graph.svg');
console.log('Graph written to:', imagePath);
// Only circular dependencies
await res.image('circular.svg', true);Note: Requires Graphviz to be installed on the system.
Generate SVG representation as Buffer.
/**
* Return Buffer with XML SVG representation of the dependency graph
* @returns Promise resolving to SVG Buffer
*/
svg(): Promise<Buffer>;Usage Example:
const res = await madge('src/');
const svgBuffer = await res.svg();
const svgString = svgBuffer.toString();
console.log(svgString); // SVG XML contentinterface MadgeConfig {
/** Base directory to use instead of the default */
baseDir?: string;
/** If shallow NPM modules should be included */
includeNpm?: boolean;
/** Valid file extensions used to find files in directories */
fileExtensions?: string[];
/** An array of RegExp for excluding modules */
excludeRegExp?: string[] | false;
/** RequireJS config for resolving aliased modules */
requireConfig?: string;
/** Webpack config for resolving aliased modules */
webpackConfig?: string;
/** TypeScript config for resolving aliased modules */
tsConfig?: string | object;
/** Layout to use in the graph */
layout?: string;
/** Sets the direction of the graph layout */
rankdir?: string;
/** Font name to use in the graph */
fontName?: string;
/** Font size to use in the graph */
fontSize?: string;
/** Background color for the graph */
backgroundColor?: string;
/** A string specifying the shape of a node in the graph */
nodeShape?: string;
/** A string specifying the style of a node in the graph */
nodeStyle?: string;
/** Default node color to use in the graph */
nodeColor?: string;
/** Color to use for nodes with no dependencies */
noDependencyColor?: string;
/** Color to use for circular dependencies */
cyclicNodeColor?: string;
/** Edge color to use in the graph */
edgeColor?: string;
/** Custom Graphviz options */
graphVizOptions?: object | false;
/** Custom Graphviz path */
graphVizPath?: string | false;
/** Custom detective options for dependency-tree and precinct */
detectiveOptions?: DetectiveOptions | false;
/** Function called with a dependency filepath (exclude subtrees by returning false) */
dependencyFilter?: Function | false;
}
interface DetectiveOptions {
/** ES6 module detection options */
es6?: {
/** Enable mixed import/require syntax detection */
mixedImports?: boolean;
/** Skip import type statements in Flow/TypeScript */
skipTypeImports?: boolean;
};
/** TypeScript module detection options */
ts?: {
/** Enable mixed import/require syntax detection */
mixedImports?: boolean;
/** Skip import type statements */
skipTypeImports?: boolean;
/** Skip dynamic import() statements */
skipAsyncImports?: boolean;
};
/** TSX module detection options */
tsx?: {
/** Skip dynamic import() statements */
skipAsyncImports?: boolean;
};
}Common errors that may be thrown:
image() method rejects Promise if imagePath is missing.image(), .svg(), .dot()) may throw Error if Graphviz is not found when requiredUsage Example:
try {
const res = await madge('src/');
console.log(res.obj());
} catch (error) {
if (error.message.includes('path argument not provided')) {
console.error('Please provide a valid path');
} else if (error.code === 'ENOENT') {
console.error('File or directory not found');
} else {
console.error('Analysis failed:', error.message);
}
}