npm & Package Management
npm is the world's largest software registry. Learn how to install packages, manage versions with SemVer, write scripts, and understand the package.json file structure for any JavaScript project.
What is npm and how do I use it?
npm is the package manager that comes with Node.js. It downloads open-source libraries into node_modules and records them in package.json. Use npm init -y to start a project, npm install lodash to add a dependency, npm install -D vite for a development-only tool, and npm run <script> to run commands defined in package.json.
npm init -y
npm install date-fns # dependency
npm install -D vitest # devDependency
npm run dev # runs "scripts.dev" from package.json
npx create-vite@latest my-app # run a package without installing itEssential Commands
Init & Install
$ npm init -y$ npm install$ npm install express$ npm install jest -D$ npm install -g typescriptRemove & Update
$ npm uninstall lodash$ npm update$ npm outdated$ npm update express$ npm install express@latestScripts
$ npm start$ npm test$ npm run dev$ npm run build$ npm run lintInspect & Audit
$ npm list --depth=0$ npm info express$ npm audit$ npm audit fix$ npm cinpm vs pnpm vs Yarn
| Feature | npm | pnpm | Yarn |
|---|---|---|---|
| Speed | Baseline | Fastest (hardlinks) | Fast |
| Disk usage | Duplicate copies | Shared store (tiny) | Moderate |
| Lockfile | package-lock.json | pnpm-lock.yaml | yarn.lock |
| Workspaces | ✅ v7+ | ✅ Excellent | ✅ v1+ |
| Strictness | Hoisting (permissive) | Strict (no phantom deps) | Plug'n'Play optional |
| Install command | npm install | pnpm install | yarn |
| Run script | npm run dev | pnpm dev | yarn dev |
Common Pitfalls
Interactive Demo
Code Editor
<pre># start a project
npm init -y
# add a library (goes in "dependencies")
npm install date-fns
# add a dev tool (goes in "devDependencies")
npm install -D vite
# run a script from package.json
npm run dev</pre>
<pre>// package.json
{
"name": "my-app",
"scripts": { "dev": "vite", "build": "vite build" },
"dependencies": { "date-fns": "^4.1.0" },
"devDependencies": { "vite": "^6.0.0" }
}</pre>Preview
npm: summary
Key points
- Commit
package-lock.json: it pins exact versions so every install is identical. - Never commit
node_modules; add it to.gitignore. ^1.2.3allows minor and patch updates;~1.2.3allows patches only.- Check what you install: a small package can add many dependencies and security risk.
Frequently asked questions
›What is the difference between npm and npx?
npm installs and manages packages. npx runs a package's command, downloading it temporarily if needed, without adding it to your project.
›npm, yarn or pnpm?
All three work. npm ships with Node. pnpm is faster and saves disk space. Use whichever your project already uses, and stick with one lockfile.