npm lifecycle scripts, in order
npm runs special scripts at defined points in the install, test, start, stop and publish lifecycles. This reference lists each lifecycle script in execution order with what triggers it and a typical use case, plus the pre/post naming convention that lets you hook around any command. Search by name or keyword.
How it works
Scripts live in the scripts field of package.json. Some names are reserved lifecycle hooks that npm invokes automatically: installing a package fires preinstall, install, postinstall and prepare; publishing fires prepublishOnly, prepare, prepack, postpack, publish and postpublish; and npm test, npm start, npm stop and npm restart each fire their own pre/post pair.
The general rule is the pre/post convention: for any script x, npm runs prex before and postx after. This works for the reserved lifecycle commands and for your own custom scripts. The crucial distinction to remember is prepare versus postinstall — prepare also runs before pack/publish and is skipped when your package is installed as a production dependency, which makes it the right place for build steps and git-hook installation.
Tips and examples
A typical library configuration:
{
"scripts": {
"build": "tsc",
"prebuild": "rimraf dist",
"test": "vitest run",
"pretest": "eslint .",
"prepare": "npm run build",
"prepublishOnly": "npm test"
}
}
prebuildcleans beforebuild;pretestlints before tests — both via the naming convention alone.preparebuilds on local install and before publish;prepublishOnlyruns tests as a publish gate.- Skip lifecycle scripts in untrusted installs with
npm install --ignore-scripts. - Note that npm v7+ tightened auto-hook behaviour, but the reserved lifecycle hooks and the
pre/postpattern fornpm runscripts still apply as described.