tezvyn:

Diamond dependencies and nested node_modules

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

understanding npm's nested install layout.

OUTLINE

npm hoists one version to the top and nests the conflicting version under the dependent package; both coexist on disk.

WHAT THIS TESTS This examines whether you understand npm's deduplication and nesting strategy and the subtle bugs that arise when multiple copies of a supposedly single library load at once.

A GOOD ANSWER COVERS Modern npm uses a flat install where it hoists one version of each package to the top-level node_modules whenever it can satisfy the most consumers. When two dependencies need incompatible major versions, npm cannot hoist both, so it places one at the top and nests the other copy inside the requiring package's own node_modules directory. Node's resolution then walks up from each module, so lib-A finds its lodash 3 and lib-B finds its lodash 4. Both physically exist, the build works, and each consumer is happy. The trouble is duplication: the bundle or install is larger, and crucially any library that assumes it is a singleton breaks. If two copies of such a library load, they hold separate internal state, instanceof checks against the other copy's classes fail, and shared registries or contexts silently diverge.

COMMON WRONG ANSWERS Saying npm can only ever install one version of a package, that the diamond always causes an install error, or ignoring the singleton hazard entirely. Another mistake is assuming hoisting is deterministic regardless of install order.

LIKELY FOLLOW-UPS How peerDependencies prevent duplicate singletons, why instanceof fails across copies, how bundlers dedupe, and how pnpm's symlinked store changes this picture.

ONE CONCRETE EXAMPLE A UI app pulls in two component libraries that each depend on a different major of a shared context library. npm hoists one and nests the other, so two copies of that context library run. A provider rendered with copy one is invisible to a consumer reading copy two, because they reference different module instances, and instanceof checks across them return false. The fix is declaring the context library as a peerDependency so the host app supplies one shared copy.

Read the original → npm.github.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.