Course contentsShow
← JavaScript
Lesson 2505 of 2,72351. Package ManagementFree lesson

Dependency Hoisting and Deduplication

Understand how npm flattens the dependency tree to avoid duplicate packages in node_modules.

Dependency Hoisting and Deduplication

What you'll learn: How npm flattens your dependency tree to avoid storing duplicate packages and reduce the size of node_modules.

The Problem with Nested Dependencies

Imagine if every package installed its own private copy of every dependency. If five packages all depend on lodash@4.17.21, you'd have five identical copies of lodash cluttering your disk. Early versions of npm actually worked this way, creating deeply nested node_modules folders that could become absurdly large.

How Hoisting Works

Hoisting is npm's solution: it "lifts" shared dependencies up to the top level of node_modules whenever possible. Instead of storing:

node_modules/
  packageA/
    node_modules/
      lodash/
  packageB/
    node_modules/
      lodash/

npm flattens (hoists) to:

node_modules/
  lodash/
  packageA/
  packageB/

Now both packageA and packageB can share the single lodash installation at the top level.

Deduplication in Action

Deduplication means npm identifies when multiple packages require compatible versions of the same dependency. If packageA wants lodash@^4.17.0 and packageB wants lodash@^4.17.20, npm installs just one copy (4.17.21, for example) that satisfies both.

When versions conflict (say, one package needs lodash@3.x), npm keeps the incompatible version nested under that specific package while hoisting the most common version to the top.

Why This Matters

Hoisting dramatically reduces disk space, speeds up installations, and simplifies module resolution. Your lockfile records the flattened structure, ensuring everyone on your team gets the same deduplicated tree.

Key Takeaway: Dependency hoisting flattens your node_modules tree by lifting shared dependencies to the top level, while deduplication ensures compatible versions are stored only once, making your project faster and leaner.