Concept Explanation
No serious app is built entirely from scratch — you borrow code. npm (Node Package Manager) is a giant warehouse of over two million free packages: date libraries, web frameworks, test tools. You "order" a part and it shows up in a folder called node_modules, ready to import.
Every Node project has a package.json — the receipt that lists exactly which packages (and which versions) your app depends on. Share that one file and anyone can rebuild the whole node_modules folder with a single command.
Syntax or Core Structure
npm init -y # create a package.json
npm install express # download a package + record it
npm install --save-dev vitest # a dev-only dependency
Then use it in code:
import express from "express"; // ES Modules
// or, in CommonJS:
const express = require("express");
Real World Example
The Lockfile: Alongside package.json, npm writes package-lock.json — it pins the exact version of every nested dependency so your teammate's install is byte-for-byte identical to yours. Reproducible builds, no "works on my machine."
Common Mistakes
- Committing node_modules: It can be hundreds of megabytes. Add it to
.gitignore— the lockfile is enough to rebuild it. - Ignoring Semver:
^1.2.0allows minor updates;~1.2.0only patches. Misreading these breaks builds. - Global Installs Everywhere: Prefer local project installs so each project controls its own versions.
Best Practices
- Commit the Lockfile: Always check in
package-lock.jsonfor reproducible installs. - Audit Dependencies: Run
npm auditto catch known security holes. - Fewer Dependencies: Every package is code you didn't review. Don't add a library to save three lines.
Practice Exercises
- The Setup: Run
npm init -yand install any package. Inspect the newpackage.json. - The Script: Add a
"start": "node index.js"entry to thescriptssection and run it withnpm start. - The Detective: Open
package-lock.jsonand explain why it's so much longer thanpackage.json.