Rasmus Olsson

Visualizing dependencies in React

Tags: react,
April 21, 2021

At some point in time, it might become handy to visualize your dependencies. Maybe you have a refactoring initiative and want an easy way to display or grasp how things look. In this post, we will take a look at some tools that might be helpful in that.

Dependency cruiser

Probably the most popular tool to visualize dependencies for React. It can combine a set of rules, visualize and validate the different dependencies.

npm install --save-dev dependency-cruiser

To visualize the structure as a picture we can pipe the result to graphviz.

You can install graphviz at https://www.graphviz.org/ or with chocolatey or most other package managers:

choco install graphviz

Add to package.json:

"scripts": { "architecture": "depcruise --include-only \"^src\" --output-type dot src | dot -T svg > dependencygraph.svg" }

Run:

yarn architecture

Running this on my redux-toolkit-typescript-example app would result in:

dependencygraph

React sight

React sight is a small extension that can be used to visualize components and dom elements as a graph. Its can be quite buggy and works best running on a local setup during development. Note that it also can be quite cpu heavy on big applications.

  1. Install react sight plugin
  2. Install react developer tools
  3. Install redux DevTools
  4. Inspect element and you should be able to see react sight in the tabs to the right. Clicking it will start a process of building the graphs, components and dom elements.

Example:

react-sight

Madge

Madge is another tool that can help visualize dependencies. It has easy to use cli that can be combined with different flags such as catching circular dependencies.

npm install --save-dev madge

To visualize the structure as a picture we need graphviz.

You can install graphviz at https://www.graphviz.org/ or with chocolatey or most other package managers.

choco install graphviz

Add to package.json:

"scripts": { "architecture": "madge --extensions ts,tsx --image graph.svg src/" }

Note the --extensions flag. By default it includes .js files.

Running this on my redux-toolkit-typescript-example app would result in:

madge

Conclusion

Visualizing dependencies can be a great tool in some cases and it requires quite a low effort to set up. I find it most useful when discussing new conventions, planning larger features or simply obtaining a reality check on how the actual structure look.

Happy Coding!

please share