npm & package.json
Project Initialization
Create and configure a project
npm init -y # create package.json with defaults
npm init # interactive setup
package.json structure
{
"name": "netcheck",
"version": "1.0.0",
"type": "module",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"test": "node --test",
"lint": "eslint src/"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"eslint": "^9.0.0"
}
}
"type": "module" enables ESM (import/export). Without it, Node uses CommonJS (require).
Dependency Management
Install, remove, update
npm install express # add dependency
npm install -D eslint # add dev dependency
npm install # install all from package.json
npm uninstall express # remove
npm update # update within semver range
npm outdated # show outdated packages
npm ls # dependency tree
npm ls --depth=0 # top-level only
Version Ranges
Semver in package.json
{
"dependencies": {
"exact": "4.18.2",
"patch": "~4.18.2",
"minor": "^4.18.2",
"any": "*"
}
}
^ (caret) allows minor and patch updates: ^4.18.2 matches >=4.18.2 <5.0.0. ~ (tilde) allows only patch updates: ~4.18.2 matches >=4.18.2 <4.19.0. Caret is the default.
Scripts
npm run and lifecycle scripts
npm start # runs "start" script
npm test # runs "test" script
npm run dev # runs custom "dev" script
npm run lint # runs custom "lint" script
Script composition
{
"scripts": {
"prebuild": "rm -rf dist",
"build": "tsc",
"postbuild": "echo 'Build complete'",
"dev": "node --watch src/index.js",
"test": "node --test src/**/*.test.js",
"lint": "eslint src/",
"format": "prettier --write src/"
}
}
pre* and post* scripts run automatically before/after the named script. npm start and npm test do not need run.
npx
Execute packages without installing
npx create-react-app my-app # run without installing globally
npx eslint src/ # use project-local eslint
npx -p node@18 node -e 'console.log(process.version)' # specific node version
Lock File
package-lock.json
# Regenerate lock file
rm -rf node_modules package-lock.json && npm install
# Install exact versions from lock file (CI)
npm ci # clean install — faster, strict
npm ci is for CI/CD: it installs exactly what is in package-lock.json, removes node_modules first, and fails if the lock file is out of sync. Always commit package-lock.json.
Global Packages
System-wide tools
npm install -g typescript # install globally
npm list -g --depth=0 # list global packages
npm root -g # global packages directory
npx which eslint # find executable path
Prefer npx over global installs — it uses the project-local version and avoids version conflicts.