npm Scripts Reference

Lifecycle npm script hooks in execution order with use cases.

Reference for npm lifecycle scripts — preinstall, install, postinstall, prepare, prepublishOnly, pretest, prestart and more — in execution order, with what triggers each and the pre/post hook naming convention.

What is the difference between prepare and postinstall?

postinstall runs after dependencies are installed for any install. prepare runs on local installs AND before the package is packed or published, but is skipped when installing the package as a dependency in production. Use prepare to build before publish and to install git hooks.

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 postinstallprepare 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"
  }
}
  • prebuild cleans before build; pretest lints before tests — both via the naming convention alone.
  • prepare builds on local install and before publish; prepublishOnly runs 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/post pattern for npm run scripts still apply as described.