HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1391 min read

Phantom Dependencies (node_modules Hoisting)

The Import That Works Until It Doesn't

Developer toolingdeveloper tooling / package management

Friday, 17:40

You ship a two-line change. Builds green locally. CI green. Staging crashes on boot:

Error: Cannot find module 'ms'

You grep. There it is, in src/retry.js, written three weeks ago:

const ms = require('ms')

It has always worked. It is NOT in your package.json. It never was.

What actually happened

npm and yarn flatten ("hoist") the dependency tree. You declared express; express depends on ms; npm parks both at the top level:

node_modules/
  express/
  ms/        ← you never asked for this
  send/

Node's resolver walks up directories looking for node_modules/<name>. It does not care who declared what. So require('ms') resolves happily, and your package.json quietly stops describing your real imports.

Staging broke because one transitive bump changed the layout — a sub-dep got a nested copy instead of a hoisted one. Your phantom evaporated.

Reproduce it in 20 seconds

mkdir t && cd t && npm init -y && npm i express
node -e "require('ms'); console.log('phantom works')"
grep ms package.json      # silence

Why pnpm doesn't have this class of bug

pnpm builds node_modules out of symlinks: your root node_modules contains ONLY what you declared. express's own deps live under node_modules/.pnpm/ and are visible only to express. So require('ms') is MODULE_NOT_FOUND on your laptop at second 1 — not in staging at 17:40.

That strictness is the real argument for pnpm, far more than the disk savings everyone quotes.

Find yours in one command

npx depcheck

Missing dependencies
* ms: ./src/retry.js
* semver: ./src/version.js

Every line there is a phantom waiting for a bad Tuesday.

The nuance people get wrong

  • "The lockfile makes it reproducible." A lockfile pins VERSIONS, not the hoisted directory layout. Same lockfile, different npm version, different tree.
  • Patching it with "ms": "*" — now you've declared an unbounded range. Pin what you actually tested.
  • A devDependency imported from runtime code works all through local dev and dies on npm ci --omit=dev. Same bug, different door.
  • Monorepos double the surface: workspace A can import workspace B's dependency through the shared root node_modules, so A builds green until B drops that dep.

Your exercise

Run npx depcheck on your main repo. For each "missing" entry, decide if the import is genuine — if yes, npm i <pkg> so it's declared. Then, on a throwaway branch, try pnpm install and boot the app. Whatever explodes was coupling you didn't know you had.