How to manage dependencies with npm

· Category: JavaScript

Short answer

npm is the default package manager for Node.js. Use npm install to add packages, npm update to bump versions, and package-lock.json to lock dependency trees.

Steps

  1. Install a package: bash npm install lodash
  2. Install as a dev dependency: bash npm install --save-dev jest
  3. Update packages: bash npm update
  4. Use semantic versioning: - ^1.2.3 allows minor and patch updates. - ~1.2.3 allows patch updates only. - 1.2.3 pins the exact version.
  5. Commit package-lock.json to ensure reproducible installs.

Tips

  • Use npm ci in CI/CD for faster, deterministic installs.
  • Audit dependencies regularly with npm audit and npm audit fix.

Common issues

  • Conflicting peer dependencies cause installation errors.
  • Deleting node_modules and reinstalling often resolves phantom dependency issues.