madge

repository·master·Indexed 27 days ago

https://github.com/pahen/madge

A developer tool for generating visual module dependency graphs, identifying circular dependencies, and analyzing module relationships in JavaScript and CSS preprocessor files. It provides both a CLI and a programmatic API to extract dependency data, find orphans and leaves, and export graphs in DOT, SVG, or image formats using Graphviz.

Tokens
2.6K
Snippets
5
Records
19
Agent score
93%

What's inside madge

  1. Install Graphviz for visual graphs

    master

    Graphviz is required if you want to generate visual graphs in formats like SVG or DOT.

    Mac OS X:

    brew install graphviz || port install graphviz

    Ubuntu:

    apt-get install graphviz
  2. Configure mixed imports and type imports

    master

    Madge uses dependency-tree and precinct. You can fine-tune how it handles specific syntax via detectiveOptions in your configuration.

    Enable mixed ES6 + CommonJS imports:

    {
      "detectiveOptions": {
        "es6": { "mixedImports": true }
      }
    }

    Ignore import type in ES6 + Flow:

    {
      "detectiveOptions": {
        "es6": { "skipTypeImports": true }
      }
    }

    Ignore import in type annotations in TypeScript:

    {
      "detectiveOptions": {
        "ts": { "skipTypeImports": true }
      }
    }

    Ignore dynamic imports in TypeScript:

    {
      "detectiveOptions": {
        "ts": { "skipAsyncImports": true },
        "tsx": { "skipAsyncImports": true }
      }
    }
  3. Configure Madge

    master

    Configuration can be provided via a .madgerc file in your project or home folder, or directly in your package.json under a madge key.

    PropertyTypeDefaultDescription
    baseDirStringnullBase directory to use instead of the default
    includeNpmBooleanfalseIf shallow NPM modules should be included
    fileExtensionsArray['js']Valid file extensions used to find files
    excludeRegExpArrayfalseAn array of RegExp for excluding modules
    requireConfigStringnullRequireJS config for resolving aliased modules
    webpackConfigStringnullWebpack config for resolving aliased modules
    tsConfigString|ObjectnullTypeScript config (path or object) for resolving aliased modules
    layoutStringdotLayout to use in the graph
    rankdirStringLRSets the direction of the graph layout
    fontNameStringArialFont name to use in the graph
    fontSizeString14pxFont size to use in the graph
    backgroundColorString#000000Background color for the graph
    nodeShapeStringboxShape of a node
    nodeStyleStringroundedStyle of a node
    nodeColorString#c6c5feDefault node color
    noDependencyColorString#cfffacColor for nodes with no dependencies
    cyclicNodeColorString#ff6c60Color for circular dependencies
    edgeColorString#757575Edge color
    graphVizOptionsObjectfalseCustom Graphviz options
    graphVizPathStringnullCustom Graphviz path
    detectiveOptionsObjectfalseCustom detective options
    dependencyFilterFunctionfalseFunction called with a dependency filepath (return false to exclude subtrees)
  4. Fix 'Error: write EPIPE' when exporting graphs

    master

    If you encounter Error: write EPIPE while attempting to export a graph to an image, it is likely because Graphviz is not installed or not accessible in your system's PATH.

    On Windows: Graphviz does not automatically add itself to the PATH variable during installation. You must manually add the folder containing gvpr.exe (typically %Graphviz_folder%/bin) to your system's PATH environment variable.

  5. Fix 'Graphviz not built with triangulation library' error

    master

    If you receive the error Graphviz not built with triangulation library when using the sfdp layout on macOS via Homebrew, you must install the gts library explicitly. Run the following commands:

    brew uninstall graphviz
    brew install gts
    brew install graphviz
  6. Debug Madge issues

    master

    If you encounter problems or missing dependencies, use the --debug flag to enable detailed output. If files are missing, you can also use the --warning flag to see which files were skipped.

    madge --debug path/src/app.js
  7. Use the Madge API

    master

    The madge(path, config) function is the primary entry point for the API.

    • path: A single file, a directory, an array of files/directories, or a predefined tree object.
    • config: An optional configuration object.

    Returns a Promise that resolves to a Madge instance object.

    const madge = require('madge');
    madge('path/to/app.js').then((res) => {
    	// Use the Madge instance methods here
    });
  8. Extract dependency data with Madge instance methods

    master

    Once the Madge instance is resolved, use these methods to extract information:

    • .obj(): Returns an Object containing all dependencies.
    • .warnings(): Returns an Object of warnings (e.g., skipped files).
    • .circular(): Returns an Array of modules with circular dependencies.
    • .circularGraph(): Returns an Object containing only circular dependencies.
    • .depends(modulePath): Returns an Array of all modules that depend on the specified module.
    • .orphans(): Returns an Array of modules that no one is depending on.
    • .leaves(): Returns an Array of modules that have no dependencies.
    • .dot([circularOnly: boolean]): Returns a Promise resolving to a DOT representation string. Set circularOnly to true to include only circular dependencies.
    • .image(imagePath, [circularOnly: boolean]): Writes the graph as an image to imagePath. The format is determined by the file extension. Returns a Promise resolving to the full path of the written image.
    • .svg(): Returns a Promise resolving to a Buffer containing the XML SVG representation.
  9. Configure Madge options

    master

    When initializing Madge, you can pass a config object to override default settings. Key configuration options include:

    KeyDefaultDescription
    baseDirnullBase directory for resolution
    excludeRegExpfalseRegExp to exclude files
    fileExtensions['js']Array of file extensions to include
    includeNpmfalseWhether to include npm modules in the graph
    tsConfignullPath to a tsconfig.json file (string) or parsed config object
    webpackConfignullWebpack configuration object
    rankdir'LR'Graphviz direction (e.g., 'LR', 'TB')
    layout'dot'Graphviz layout engine
    nodeColor'#c6c5fe'Color of the nodes
    edgeColor'#757575'Color of the edges
    cyclicNodeColor'#ff6c60'Color of nodes involved in circular dependencies
    graphVizPathfalsePath to the Graphviz executable
  10. Choose a Graphviz layout for better graph readability

    master

    If the generated image is difficult to read, try using a different Graphviz layout engine. Available layouts include:

    • dot: Hierarchical or layered drawings of directed graphs. Best for directed edges.
    • neato: Spring model layouts. Best for graphs with fewer than ~100 nodes where the structure is unknown.
    • fdp: Spring model layouts that reduce forces rather than working with energy.
    • sfdp: A multiscale version of fdp designed for large graphs.
    • twopi: Radial layouts where nodes are placed on concentric circles based on distance from a root node.
    • circo: Circular layout, suitable for diagrams of multiple cyclic structures (e.g., telecommunications networks).