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
- Install a package:
bash npm install lodash - Install as a dev dependency:
bash npm install --save-dev jest - Update packages:
bash npm update - Use semantic versioning:
-
^1.2.3allows minor and patch updates. -~1.2.3allows patch updates only. -1.2.3pins the exact version. - Commit
package-lock.jsonto ensure reproducible installs.
Tips
- Use
npm ciin CI/CD for faster, deterministic installs. - Audit dependencies regularly with
npm auditandnpm audit fix.
Common issues
- Conflicting peer dependencies cause installation errors.
- Deleting
node_modulesand reinstalling often resolves phantom dependency issues.