Managing npm Packages
1. Initializing Package
| Command | Action |
npm init | Interactive wizard |
npm init -y | Accept defaults |
npm init <initializer> | Run create-<name> (e.g. npm init vite) |
2. Installing Packages
| Command | Effect |
npm install | Install from package.json |
npm i pkg | Add to dependencies |
npm i pkg@1.2.3 | Specific version |
npm ci | Clean install from lockfile (CI) |
npm i --omit=dev | Production-only deps |
3. Installing Dev Dependencies
| Command | Effect |
npm i -D pkg | Adds to devDependencies |
npm i --save-dev pkg | Same as above |
4. Installing Global Packages
| Command | Notes |
npm i -g pkg | Installs to global prefix |
npm ls -g --depth=0 | List global installs |
npm uninstall -g pkg | Remove global |
Note: Prefer npx or local devDependencies over globals to avoid version drift.
5. Updating Packages
| Command | Effect |
npm outdated | Show available updates |
npm update | Update within semver range |
npm i pkg@latest | Bump to latest, update package.json |
npx npm-check-updates -u | Bump all to latest |
6. Removing Packages
| Command | Effect |
npm uninstall pkg | Remove + update package.json |
npm rm pkg | Alias |
7. Using npx for Package Execution
| Form | Behavior |
npx cowsay hi | Run binary, fetch if needed |
npx -p pkg cmd | Specify package explicitly |
npx pkg@1.2.3 | Pin version for one-off |
npx -y create-react-app my-app | Skip install prompt |
8. Understanding Semantic Versioning (^, ~, exact)
| Range | Matches | Use |
1.2.3 | Exact | Strict pin |
^1.2.3 | >=1.2.3 <2.0.0 | Default; minor + patch updates |
~1.2.3 | >=1.2.3 <1.3.0 | Patch updates only |
1.x | Any 1.y.z | Loose |
* / latest | Anything | Avoid in apps |
>=1.2 <2 | Compound | Custom range |
9. Managing Lock Files
| File | Purpose |
package-lock.json | Pin transitive deps (commit it) |
npm shrinkwrap | Publishable lock for libs |
npm ci | Strict install from lock |
10. Auditing Security
| Command | Effect |
npm audit | Show vulnerabilities |
npm audit fix | Auto-fix within semver |
npm audit fix --force | Allow breaking upgrades |
npm audit --omit=dev | Production only |
11. Publishing Packages
Publish Workflow
npm login
- Bump version:
npm version patch|minor|major
- Build (if needed)
npm publish (add --access public for scoped packages)
npm dist-tag add pkg@1.2.3 latest
| Field | Use |
"private": true | Prevent accidental publish |
"files" | Whitelist what gets published |
.npmignore | Exclude paths |
12. Using Workspaces
Example: Monorepo workspaces
{
"name": "monorepo",
"private": true,
"workspaces": ["packages/*", "apps/*"]
}
| Command | Effect |
npm i -w pkg-a | Install in specific workspace |
npm run build -ws | Run in all workspaces |
npm run test -w pkg-a | Run in one workspace |