pahen / madge

Create graphs from your CommonJS, AMD or ES6 module dependencies
MIT License
9.08k stars 317 forks source link

Calculate dependency require path #408

Open flaviut opened 7 months ago

flaviut commented 7 months ago

This is not a bug or an issue, but sharing something that helps me.

I needed to figure out why a certain file was included in a bundle, so I wrote this script to help figure it out:

const args = process.argv.slice(2);
if (args.length !== 2 || args.includes('--help') || args.includes('-h')) {
    console.log("Usage: node madge_dfs.js <startNode> <endNode>");
    console.log("Expects a JSON graph from 'madge' on stdin.");
    console.log()
    console.log("Example: node script.js start.js target.js");
    process.exit(1);
}

let graph = '';

process.stdin.on('data', function(data) {
    graph += data;
});

process.stdin.on('end', function() {
    const parsedGraph = JSON.parse(graph);
    const startNode = args[0];
    const endNode = args[1];

    const path = findPath(parsedGraph, startNode, endNode);
    console.log(path.join(' requires\n'))
});

function findPath(graph, start, end, visited = new Set()) {
    if (!graph[start]) return null;

    visited.add(start);

    for (let dependency of graph[start]) {
        if (dependency === end) {
            return [start, end];
        }

        if (!visited.has(dependency)) {
            const path = findPath(graph, dependency, end, visited);
            if (path !== null) {
                return [start, ...path];
            }
        }
    }

    return null;
}

Example usage:

$ npx madge --json index.ts | node script.js index.ts ../../config.ts
index.ts requires
../intermediate1.ts requires
../intermediate2.ts requires
../../config.ts