Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate dependency require path #408

Open
flaviut opened this issue Apr 3, 2024 · 0 comments
Open

Calculate dependency require path #408

flaviut opened this issue Apr 3, 2024 · 0 comments

Comments

@flaviut
Copy link

flaviut commented Apr 3, 2024

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant