Why is `node_modules` so heavy?
Transitive dependencies, deduplication, lockfiles and the small-packages philosophy.
node_modules now has 287 folders and 140 megabytes. Who are all these people, and why are they living at my place rent-free?Every package has its own package.json with its own dependencies. And those have theirs. npm installs the whole tree: the dependencies of dependencies are called transitive. You asked for one framework — it asked for a router and an HTTP client, they asked for path utilities, request retries, time parsing… One npm install easily brings in hundreds of packages.
const registry = {
"web-app": ["router", "http-client"],
"router": ["path-utils"],
"http-client": ["path-utils", "retry"],
"path-utils": [],
"retry": ["ms"],
"ms": [],
};
function allDependencies(name, seen = new Set()) {
for (const dep of registry[name]) {
if (!seen.has(dep)) {
seen.add(dep);
allDependencies(dep, seen);
}
}
return seen;
}
console.log("Direct:", registry["web-app"].length);
console.log("Total:", [...allDependencies("web-app")]);path-utils is needed by two packages but installed once.Both the router and the HTTP client need path-utils. npm puts one copy at the root of node_modules, and both packages find it. That's deduplication (dedupe). But if one needs ^1.0.0 and the other ^2.0.0, a single copy can't serve both: one version goes to the root, and the other into a nested node_modules inside the package that needs it. That's how a project ends up with duplicates of the same package.
Why so many packages? In the JavaScript world it's customary to make them tiny: one function, one package (ms, is-number, the infamous left-pad). It happened for historical reasons: The result: projects built from thousands of little bricks. Convenient — and fragile: in a chain of a thousand packages, one broken or malicious one is enough.
- for a long time JavaScript had no rich standard library — no
padStart, no convenient dates — so everyone filled in the gaps; - npm made publishing free and instant;
- in the browser every kilobyte counts, and pulling a huge library in for one function felt wasteful.
What else adds weight: node_modules holds more than the files that reach the browser. There are TypeScript types, sources, documentation and, for bundlers, ready-made programs for different operating systems. Your site's users download none of it: the bundler takes only the code you actually imported. A heavy node_modules is weight on the developer's disk, not in the browser.
How people live with it:
- npm ci installs strictly from the lockfile — that's what servers that build and check the project do;
npm ls nameshows who brought a package into the project;npm auditlooks for packages with known vulnerabilities;- the pnpm package manager stores each package version on disk once and gives projects links to it.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.