Scripts & Lifecycle Hooks
The scripts object is the build system most JavaScript projects actually use: named shell commands that npm runs with a prepared environment. On top of the commands you name yourself, npm runs lifecycle scripts automatically around installs, packing and publishing. This lesson covers both; the Node.js course introduces the basics.
What npm run sets up
Before running a script, npm:
- puts
./node_modules/.bin(and the.binof every parent folder) at the front ofPATH, soesbuildworks withoutnpx; - runs it with
shon Unix andcmd.exeon Windows (script-shellchanges that); - exports
npm_package_name,npm_package_version,npm_lifecycle_event(the script's name) and the npm config asnpm_config_*; - runs
pre<name>before andpost<name>after, if they exist; - passes everything after
--to the script as extra arguments.
mkdir -p tasks && cd tasks
cat > package.json <<'JSON'
{
"name": "tasks",
"version": "1.4.0",
"scripts": {
"prebuild": "echo \"[$npm_lifecycle_event] cleaning\" && rm -rf dist",
"build": "mkdir -p dist && echo \"[$npm_lifecycle_event] $npm_package_name@$npm_package_version\" > dist/out.txt && cat dist/out.txt",
"postbuild": "echo \"[$npm_lifecycle_event] done\"",
"greet": "node greet.js",
"where": "echo \"$PATH\" | tr ':' '\\n' | head -1"
}
}
JSON
echo 'console.log("args:", process.argv.slice(2));' > greet.js
npm run build
npm run greet -- --name=Ada --loud
npm run -s where
npm run
> tasks@1.4.0 prebuild
> echo "[$npm_lifecycle_event] cleaning" && rm -rf dist
[prebuild] cleaning
> tasks@1.4.0 build
> mkdir -p dist && echo "[$npm_lifecycle_event] $npm_package_name@$npm_package_version" > dist/out.txt && cat dist/out.txt
[build] tasks@1.4.0
> tasks@1.4.0 postbuild
> echo "[$npm_lifecycle_event] done"
[postbuild] done
> tasks@1.4.0 greet
> node greet.js --name=Ada --loud
args: [ '--name=Ada', '--loud' ]
/home/learner/tasks/node_modules/.bin
Scripts available in tasks@1.4.0 via `npm run`:
prebuild
echo "[$npm_lifecycle_event] cleaning" && rm -rf dist
build
mkdir -p dist && echo "[$npm_lifecycle_event] $npm_package_name@$npm_package_version" > dist/out.txt && cat dist/out.txt
postbuild
echo "[$npm_lifecycle_event] done"
greet
node greet.js
where
echo "$PATH" | tr ':' '\n' | head -1
-s (--silent) suppresses npm's own > tasks@1.4.0 where banner, which is handy when a script's output is piped into another command. Plain npm run lists the scripts.
Failure is an exit code
Scripts chain with &&, so the first failing command stops the chain, and npm exits non-zero, which fails a CI job:
mkdir -p tasks && cd tasks
cat > package.json <<'JSON'
{
"name": "tasks",
"version": "1.0.0",
"scripts": {
"lint": "echo linting && exit 3",
"test": "echo testing",
"check": "npm run lint && npm test"
}
}
JSON
npm run -s check; echo "exit code: $?"
npm test
npm run missing --if-present; echo "exit code: $?"
npm run missing 2>&1 | head -1linting
exit code: 3
> tasks@1.0.0 test
> echo testing
testing
exit code: 0
npm error Missing script: "missing"
npm test, npm start, npm stop and npm restart are shorthands that don't need run. --if-present makes a missing script a no-op, useful in workspaces where not every package has a lint script.
Lifecycle scripts
Some script names are reserved: npm runs them at fixed points. The ones you will use:
| Script | Runs on | Use it for |
|---|---|---|
preinstall, install, postinstall |
npm install (yours and in every dependency that defines them) |
native builds; avoid in libraries |
prepare |
local npm install (no args), npm pack, npm publish, and git-dependency installs |
building a package installed from git, setting up git hooks |
prepack / postpack |
npm pack, npm publish |
building dist/ right before packing |
prepublishOnly |
npm publish only |
the last safety check: tests, lint |
preversion, version, postversion |
npm version |
tests before bumping, git push --follow-tags after |
Watch the order during a publish:
mkdir -p lib && cd lib
cat > package.json <<'JSON'
{
"name": "@learner/lifecycle-demo",
"version": "1.0.0",
"files": ["dist"],
"scripts": {
"prepare": "echo ' hook: prepare'",
"prepublishOnly": "echo ' hook: prepublishOnly'",
"prepack": "echo ' hook: prepack (building)' && mkdir -p dist && echo 'module.exports = 42;' > dist/index.js",
"postpack": "echo ' hook: postpack'",
"publish": "echo ' hook: publish'",
"postpublish": "echo ' hook: postpublish'"
}
}
JSON
echo "== npm install"; npm install 2>&1 | grep '^ hook'
echo "== npm pack"; npm pack 2>&1 | grep -E '^ hook|^learner-'
echo "== npm publish"; npm publish 2>&1 | grep -E '^ hook|^\+'== npm install
hook: prepare
== npm pack
hook: prepack (building)
hook: prepare
hook: postpack
learner-lifecycle-demo-1.0.0.tgz
== npm publish
hook: prepublishOnly
hook: prepack (building)
hook: prepare
hook: postpack
hook: publish
hook: postpublish
+ @learner/lifecycle-demo@1.0.0
prepare runs on a plain npm install in the project and again on every pack. During a publish the order is prepublishOnly → prepack → prepare → postpack → upload → publish → postpublish. prepack built dist/ just in time, so the tarball contains a fresh build even though dist/ was never committed. That is the usual pattern for libraries: "prepack": "npm run build".
Note: pnpm runs
pre/posthooks only for lifecycle scripts, not for your own names likeprebuild, unless you setenable-pre-post-scripts=true. Yarn Berry doesn't run custompre/postscripts at all. Writing"build": "npm run clean && esbuild …"explicitly works everywhere and is easier to read.
Cross-platform scripts
Scripts run in the system shell, so rm -rf dist or FOO=1 node x.js fail on Windows' cmd.exe. Options, from simplest:
- write the step in Node:
"clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\""; - move bigger steps into a
scripts/build.mjsfile and runnode scripts/build.mjs; - set
script-shellto Git Bash on Windows machines (a per-developer.npmrcsetting).
Test yourself
Why can a script call esbuild directly without npx?
- esbuild is installed globally
- npm puts node_modules/.bin on PATH while running scripts
- npm aliases every package name
- Scripts run inside Node
Which hook runs on npm publish but not on npm pack?
- prepack
- prepare
- prepublishOnly
- postpack
How do you pass --watch to the command behind npm run build?
- npm run build --watch
- npm run build -- --watch
- npm --watch run build
- npm run build:watch