Understanding package.json
The package.json file is the heart of any Node.js project. It defines your project and its dependencies.
Creating one
bash
# Interactive setup
npm init
# Quick setup with defaults
npm init -yKey fields
json
{
"name": "my-app",
"version": "1.0.0",
"description": "A cool application",
"main": "index.js",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"next": "^14.0.0",
"react": "^18.2.0"
},
"devDependencies": {
"typescript": "^5.3.0",
"jest": "^29.7.0"
}
}dependencies vs devDependencies
dependencies — Needed at runtime. React, Express, database drivers.
devDependencies — Needed only for development. TypeScript, testing frameworks, linters.
bash
npm install react # → dependencies
npm install -D typescript # → devDependenciesVersion ranges
- ^14.0.0 — Compatible: allows 14.x.x but not 15.0.0
- ~14.0.0 — Patch only: allows 14.0.x but not 14.1.0
- 14.0.0 — Exact version
The lock file
package-lock.json records the exact version of every dependency installed. Always commit it — it ensures everyone gets the same versions.
bash
# Install exact versions from lock file
npm ci # Use this in CI/CD, not npm install