'How does npm handle circular dependency?

Just wondering, if there is a package with circular/cyclic dependency, does npm handle that? How? I have googled but couldn't find very useful results.


I can think of two kinds of problems here:

  1. Circular dependency with same version: A->B, B->C, C->A

    Does npm build the dependency like this? (Only my guess, didn't find any circular dependency to actually test on)

    [email protected]
    └─┬ [email protected]
      └─┬ [email protected]
        └── [email protected] (deduped)
    
  2. Circular dependency with different version: [email protected]>B, B->C, C->A@^1.0.0, I cannot even guess what would happen if such things exist?



Solution 1:[1]

I would strongly discourage having cyclic package dependencies. It is not just if npm can deal with that, but all the tooling you might have around your dependencies. For example, I got some weird Typescript build errors caused by the cyclic package dependencies, npm seemed to be fine. Maybe it did not notice the cycle being inside a mono repo, but Typescript was failing and there was no clear error saying "this is failing because of a cyclic dependency"

Out of experience, I would say "cyclic dependencies" tend to be a nasty pot of problems. It is not a black vs white situation, it tends to be like "undefined behavior", sometimes OK, sometimes not so OK.

I cannot tell you if npm clearly supports cyclic dependencies, but I can tell you it is more important to consider if tools can manage cyclic npm packages. Overall it is safer to assume it is not

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SystematicFrank