22

Last time i found in my project problem with circular dependencies. I resolve my problem but, i would like avoid this in future. I think about plugin which found circular dependencies in my all project and give me feedback.

Example:

File a.js:

var functionFromA= require("./b.js");
console.log("file a", functionFromA);
module.exports = {functionFromA: functionFromA};

File b.js:

var functionFromB = require("./c.js");
console.log("file b", functionFromB );
module.exports = {functionFromB : functionFromB };

File c.js:

var functionFromC = require("./a.js");
console.log("file c", functionFromC );
module.exports = {functionFromC : functionFromC }

When i run file a.js i see in console:
file c {}
file b { functionFromC: {} }
file a { functionFromB: { functionFromC: {} } }

I found "Circular Dependency Plugin" in npm but i don't know how use it? May be someone has similar problem and found a solution?

new_user
  • 255
  • 1
  • 2
  • 10

5 Answers5

61

You can find this other tool useful: https://www.npmjs.com/package/madge

is very easy to use: madge --circular [directory] give you a list of circular dependencies in your code located inside [directory]. It can also generate a graph image.

davidmpaz
  • 1,194
  • 15
  • 18
4

If you have eslint setup, you can add eslint-plugin-import and enable the import/no-cycle rule.

Etienne Martin
  • 10,018
  • 3
  • 35
  • 47
2

As davidmpaz suggested, madge is a good tool for such a thing but it only detects circular dependencies and doesn't indicate whether these circular dependencies causes a problem in your application or not.

I made a tool to detect the circular dependencies and it warns you about the problem that caused by cd. https://www.npmjs.com/package/detect-circular-deps

Ahmed Sabry
  • 434
  • 1
  • 8
  • 17
  • I wonder if it's possible to detect CD during runtime, when we import/require dynamic modules. – Milad Nov 23 '20 at 12:17
  • Circular dependencies ALMOST always indicate some poorly thought out application/library structure. I'd lean toward the `madge` tool since code will usually be clearer if circular dependencies are removed even if they "work". – Marvin Oct 04 '21 at 13:30
  • Is it possible to make it work on typescript files? – Memke Nov 22 '21 at 17:56
0

The tool that saved my life was dpdm.

One particulary great thing about it, is that it handles mix of typescript and javascript files better than madge

TLamp
  • 61
  • 3
0

We can also use skott:

skott is a minimalist developer tool that can be used to efficiently generate directed graphs from your JavaScript/TypeScript/Node.js project. It can run from CLI, for example:

skott --trackBuiltinDependencies src/index.js

Read more here

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129