Topic 24 of 55
Package.json File
Overview
The `package.json` file is the heart of a Node.js project. It defines how to run the project (`scripts`), what code it needs to run (`dependencies`), and what code it needs to build/test (`devDependencies`).
Syntax
json
{
"name": "my-awesome-api",
"version": "1.0.0",
"description": "A REST API for my app",
"main": "index.js",
"type": "module", // Enables ES Modules (import/export)
"scripts": {
"start": "node index.js", // Run in production
"dev": "nodemon index.js", // Run in development (auto-restarts)
"test": "jest" // Run tests
},
"dependencies": {
"express": "^4.18.2", // Required for the app to run
"mongoose": "^7.0.3"
},
"devDependencies": {
"nodemon": "^2.0.22", // Only needed for local development
"jest": "^29.5.0"
}
}Common Pitfalls
- The `^` symbol in dependencies means 'compatible with version'. `^4.18.2` allows `4.19.0` but not `5.0.0`. This can lead to different team members having slightly different module versions.
- To lock down exact versions for all team members, Node.js automatically generates a `package-lock.json` file. ALWAYS commit this lock file to Git.
Real-World Example
Executing scripts defined in package.json:
example
json
# Run a custom script
npm run dev
# 'start' and 'test' are special scripts that don't strictly require 'run'
npm start
npm test
# Scripts can chain commands using &&
# "build": "tsc && npm run copy-assets"