⚡ Lesson 28 of 30
npm & Package Management
Manage project dependencies, scripts, and versioning using npm and package.json.
package.json
Every Node.js project has a package.json file. Create one with:
npm init -y
# Result: package.json
{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js"
}
}
Installing Packages
# Install as runtime dependency
npm install express
npm install lodash chalk
# Install as dev-only dependency
npm install --save-dev jest prettier eslint
# Install globally
npm install -g nodemon
# Install specific version
npm install [email protected]
Semantic Versioning
Package versions follow MAJOR.MINOR.PATCH. The ^ and ~ prefixes control update ranges:
// package.json
"dependencies": {
"lodash": "^4.17.21", // accept 4.x.x updates
"express": "~4.18.0", // accept 4.18.x only
"chalk": "5.3.0" // exact version only
}
# Update all packages within ranges
npm update
# Check for outdated packages
npm outdated
npm Scripts
Define custom commands in package.json:
{
"scripts": {
"start": "node dist/index.js",
"dev": "vite",
"build": "vite build",
"test": "jest",
"lint": "eslint src/**/*.js",
"format": "prettier --write src"
}
}
# Run a script
npm run dev
npm test
Lock Files & Security
# package-lock.json locks exact versions for reproducible installs
# Always commit package-lock.json to version control
# Check for known vulnerabilities
npm audit
# Automatically fix safe vulnerabilities
npm audit fix
# List installed packages
npm ls --depth=0