56

Since NPM version 3 node modules and dependencies are all installed at the same root level. But what if I install two modules that depend on two different versions of the same module? For instance, if I install async npm i async@2.1.4, which requires lodash version 4.14.0, then I install yeoman npm i yo@1.8.5, which requires lodash version version 3.2.0, how does npm resolve this conflict?

jwerre
  • 9,179
  • 9
  • 60
  • 69
  • 8
    "In that case, each dependency with a conflicting version on the same dependency would get its own, nested copy of that conflicting dependency. That's why we describe the install tree as maximally flat – it will still allow nesting in the case of conflicts." Taken from a github issue in this topic. – user2263572 Feb 09 '17 at 21:51

1 Answers1

28

All the dependencies and the internal dependencies tries to get a place in the root of the node_modules unless there is a conflict with the same dependency, but different version. When a conflict raises, it creates a sub node_modules under each dependency needed and pushes conflicting internal libraries in it.

EXAMPLE: Here, "A" internally depends on "alpha@v1.0" and "B" depends on "alpha@v2.0". When you execute install A and B like below:

npm install A
npm install B

node_modules
|_ A
|_ alpha @v1.0
|_ B
|    |_ node_modules
|        |_ alpha @v2.0
|_ ...

NOTE: Another node_modules created under "B" inside the main node_module.

For more details: visit this post.

ShreeJ
  • 294
  • 4
  • 3
  • 3
    Is my understanding correct here in that if (continuing your example) one were to `npm install C` after the two before mentioned installs (of "A" and "B"), where "C" depends on "alpha@v2.0", then there would be two copies of "alpha@v2.0" (one under node_modules/B/node_modules/, other under "node_modules/C/node_modules/")? – Drejk Nov 14 '21 at 20:29
  • 2
    If the project has 100 more dependencies which are depending on "alpha@v2.0", then would we have 102 copies of "alpha@v2.0" code within our project tree? – ceremcem Dec 25 '21 at 21:21
  • @ceremcem Yes, total 101 copies i.e., 1 under ***main node_modules/B/node_modules/*** & 100 more each under it's respective package, check this : https://www.geeksforgeeks.org/how-does-npm-handle-version-conflicts/ – whoami - fakeFaceTrueSoul Jan 24 '23 at 20:11
  • @whoami-fakeFaceTrueSoul How come the different versions aren't stored in node_modules and then linked also in B/node_modules? It would still resolve, right? – Jack Feb 08 '23 at 22:13
  • @Jack not sure why, but that's npm functionality not to maintain a dependency of a package in other packages `node_modules`. – whoami - fakeFaceTrueSoul Feb 08 '23 at 22:40