npm & package.json
Package management — installing dependencies, scripts, semver, and lock files
Skills taught: node.npm, node.package-json, node.scripts, node.semver
package.json anatomy
{
"name": "my-api",
"version": "1.0.0",
"description": "A simple REST API",
"main": "src/index.js",
"type": "module",
"engines": { "node": ">=20.0.0" },
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"build": "tsc",
"test": "node --test",
"lint": "eslint src/",
"format": "prettier --write src/"
},
"dependencies": {
"express": "^4.18.2",
"dotenv": "^16.3.1",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.3.3",
"eslint": "^8.56.0",
"prettier": "^3.1.1"
}
}
# Initialize a new project
npm init -y # creates package.json with defaults
# Install packages
npm install express # save to 'dependencies'
npm install -D typescript # save to 'devDependencies'
npm install -g nodemon # global install (available everywhere)
npx create-vite my-app # run without installing
# Manage packages
npm uninstall lodash # remove and update package.json
npm update # update all to latest within semver range
npm outdated # show which packages have newer versions
# Run scripts (from package.json "scripts")
npm start # shorthand for npm run start
npm test # shorthand for npm run test
npm run dev # custom scripts need 'run'
npm run build
# Info
npm list # show installed packages
npm audit # check for security vulnerabilities
npm ci # clean install from lock file (CI environments)
Frequently Asked Questions
Should I commit node_modules?
Never commit node_modules — add it to .gitignore. It can contain thousands of files and hundreds of MB. Instead commit package.json and package-lock.json. Anyone cloning your repo runs `npm install` to restore node_modules. The lock file ensures they get the exact same versions you used.