npm & Package Management

npm is the default package manager for Node.js, managing dependencies, semantic versioning, and package lifecycle scripts.

Common CLI Commands

# Install dependencies from package.json
npm install

# Add production dependency (saved to dependencies by default)
npm install <package-name>

# Add development dependency (saved to devDependencies)
npm install --save-dev <package-name>

# Clean deterministic install for CI/CD (installs strictly from package-lock.json)
npm ci

# Execute binaries without global installation
npx <command>
# e.g., npx prettier --write .

# Check for outdated packages against registry
npm outdated

# Update dependencies adhering to semver constraints
npm update

# Audit and patch known security vulnerabilities
npm audit
npm audit fix

package.json Dependency Types

  • dependencies: Packages required in production runtime.
  • devDependencies: Packages only needed during local development or build (compilers, bundlers, linters, test frameworks).
  • peerDependencies: Packages expected to be provided by the consuming application (common for plugins and component libraries).

Semantic Versioning (SemVer) Prefixes

{
  "dependencies": {
    "exact-package": "1.2.3",       // Exactly 1.2.3
    "caret-package": "^1.2.3",       // Compatible minor/patch updates: >= 1.2.3 and < 2.0.0
    "tilde-package": "~1.2.3"        // Patch updates only: >= 1.2.3 and < 1.3.0
  }
}

Cache & Troubleshooting

Clear corrupted npm local cache:

npm cache clean --force

Rebuild clean dependencies:

rm -rf node_modules package-lock.json
npm install
Recommended ReadingSponsored
JavaScript: The Definitive Guide
The JS Bible
JavaScript: The Definitive Guide
By David FlanaganView on Amazon