What is npm, and what is actually in node_modules?
If you've started a JavaScript project, you've met npm and the famously large node_modules folder. Here's what's going on.
npm in brief
npm is the default package manager for Node.js. It does two main jobs:
- A registry: a huge public collection of JavaScript packages.
- A command-line tool that installs packages and runs project scripts.
Alternatives like pnpm and Yarn use the same registry with different approaches to installing.
Key files
package.json: your project's name, scripts and the dependencies it needs, with allowed version ranges.package-lock.json: records the exact versions installed, including dependencies of dependencies. Commit it so everyone installs the same thing.node_modules/: the actual installed code. Don't commit it; it can be recreated from the lockfile.
Why node_modules gets so big
Each package you install may depend on other packages, which depend on others. These transitive dependencies add up fast. Many are small, single-purpose packages.
Commands you'll use
npm install: install everything listednpm install package-name: add a dependencynpm install -D package-name: add a development-only dependencynpm run script-name: run a script defined in package.jsonnpm ci: clean, exact install from the lockfile, common in CI
Beginner tips
- If things break weirdly, deleting
node_modulesand reinstalling often helps. - Check a package's popularity, maintenance and download stats before adding it.
- Be careful with typo'd package names.
What confused you most about npm at first? Do you use npm, pnpm or Yarn?
Comments · 4
The other key thing is the lockfile. It pins exact versions so everyone on the team installs the same tree. Commit it, and don't commit node_modules.
Quick addition: if
node_modulesever acts strangely, deleting it and runningnpm installagain is the usual first fix, which is exactly why it doesn't need to be committed.Why does node_modules end up with so many nested copies of the same package? Is that how npm resolves version conflicts?
Mostly yes. If two packages need different versions of the same dependency, npm can nest a separate copy under each. Newer npm also tries to flatten and share where versions are compatible.