Andrej K
Andrej K

Reputation: 2050

How to get dependency tree/graph in NestJS?

Nestjs provides out of the box DI container very conveniently but as project gets more complex it is easy to lose the full picture of all dependencies and their order.

Question: Is there a way to get a list of all dependencies (modules, providers, controllers...) possibly in a way that can be put into a tree/graph? I'm sure Nestjs tracks this information internally and I'm wondering what would be the best way to access it.

(I found [nestjs-dependency-graph] but it scans the modules manually for metadata, doesn't find all dependencies and tends to go into infinite loop)

Upvotes: 28

Views: 13756

Answers (3)

S G
S G

Reputation: 51

Using madge npm package https://www.npmjs.com/package/madge.

Madge package will require graphviz to generate png files,You can download from here https://graphviz.org/download/. You will need to add it in environmental variable path.

then Simply run command as npx madge dist/main.js --image graph.png from your project root directory followed by nest build command.

Will generate such graph

Output Graph image

Upvotes: 1

Anton Kornus
Anton Kornus

Reputation: 687

Using madge npm package https://www.npmjs.com/package/madge

Simply as npx madge dist/main.js --image graph.png

Will generate such graph

graph

Upvotes: 5

usersina
usersina

Reputation: 1835

I've tried nestjs-spelunker like mentioned in @Jay's comment and it's really solid.

You just need to generate the graph text and paste it in the mermaid-live-editor

import { NestFactory } from '@nestjs/core';
import { SpelunkerModule } from 'nestjs-spelunker';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule);

  // 1. Generate the tree as text
  const tree = SpelunkerModule.explore(app);
  const root = SpelunkerModule.graph(tree);
  const edges = SpelunkerModule.findGraphEdges(root);
  const mermaidEdges = edges
    .filter( // I'm just filtering some extra Modules out
      ({ from, to }) =>
        !(
          from.module.name === 'ConfigHostModule' ||
          from.module.name === 'LoggerModule' ||
          to.module.name === 'ConfigHostModule' ||
          to.module.name === 'LoggerModule'
        ),
    )
    .map(({ from, to }) => `${from.module.name}-->${to.module.name}`);
  console.log(`graph TD\n\t${mermaidEdges.join('\n\t')}`);
  
  // 2. Copy and paste the log content in "https://mermaid.live/"
}

bootstrap();

Upvotes: 21

Related Questions