npm Scripts & Task Automation
Complete guide to defining and running scripts in package.json, pre/post lifecycle hooks, passing arguments, environment variables, and parallel task execution.
The scripts object in package.json allows you to define custom CLI commands and build workflows that run with local binaries in ./node_modules/.bin automatically added to the execution $PATH.
Defining Scripts
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint .",
"test": "vitest run",
"test:watch": "vitest"
}
}Running Scripts
# npm (requires 'run' for custom scripts, but 'test' and 'start' work without 'run')
npm run dev
npm test
npm start
# pnpm ('run' keyword is completely optional)
pnpm dev
pnpm build
pnpm testPassing Extra Arguments (--)
In npm, use -- to forward subsequent flags and arguments to the underlying binary:
# Runs: vitest run --coverage
npm test -- --coverage
# Runs: eslint . --fix
npm run lint -- --fixWith pnpm, flags pass directly without --:
pnpm test --coveragePre and Post Lifecycle Hooks
npm automatically runs scripts prefixed with pre and post in chronological order:
{
"scripts": {
"prebuild": "npm run clean && npm run lint",
"build": "tsc -p tsconfig.json",
"postbuild": "echo 'Build successfully completed!'"
}
}When you execute npm run build, npm executes:
prebuildbuildpostbuild
Running Scripts in Parallel vs Sequentially
- Sequential (
&&): Runs next command only if the previous command succeeds (exit code 0):"build:all": "npm run lint && npm run build" - Parallel (
concurrentlyornpm-run-all):npm install -D concurrently"dev:all": "concurrently \"npm run dev:api\" \"npm run dev:web\""
Related Guides
Peer Dependencies (`peerDependencies`)
Guide to peerDependencies in package.json, plugin architectures, peerDependenciesMeta optional peers, and resolving conflicting peer dependencies.
Semantic Versioning (SemVer) Explained
Complete guide to Semantic Versioning (SemVer 2.0.0), MAJOR.MINOR.PATCH syntax, caret (^), tilde (~), exact versions, pre-releases, and dependency pinning.