How Dependency Resolution Works
You'll learn how npm figures out which packages to install and where to place them in the node_modules tree.
The Resolution Process
When you run npm install, npm doesn't just grab packages randomly—it follows a systematic process. It starts with your package.json, reads the dependencies listed there, then fetches each package's own package.json to discover what those packages need. This continues recursively until all dependencies are mapped out.
Think of it like a family tree: your project needs package A and B. Package A needs C, and B also needs C. npm must figure out whether A and B can share the same version of C, or if they need different versions.
The node_modules Tree Structure
npm tries to flatten the dependency tree as much as possible. Ideally, all packages live at the top level of node_modules/:
node_modules/
├── package-a/
├── package-b/
└── package-c/
However, if package A needs package-c@1.0.0 and package B needs package-c@2.0.0, npm creates nested node_modules folders:
node_modules/
├── package-a/
│ └── node_modules/
│ └── package-c@1.0.0/
├── package-b/
│ └── node_modules/
│ └── package-c@2.0.0/
└── (other packages at root level)
When your code require('package-c') runs, Node.js walks up the directory tree looking for the first matching folder.
Version Conflicts and Deduplication
npm attempts to deduplicate wherever possible—if multiple packages can share a single version, that version goes at the root. The installation order can affect the final structure, which is why package-lock.json locks the exact tree for consistency.
Key Takeaway: npm resolves dependencies recursively, building a node_modules tree that's as flat as possible while handling version conflicts through nesting.