npm prepare / prepublishOnly Script Fails - Fix Release Build in CI
npm runs prepare on install and before publish/pack, and prepublishOnly only before publish. If either script fails, npm aborts - so a broken build, test, or lint in those hooks blocks the whole release.
What this error means
A publish or install fails inside prepare or prepublishOnly, with the underlying command’s error (a tsc error, a failing test, a missing tool) shown just above the npm summary. The package never publishes.
> mylib@2.0.0 prepublishOnly
> npm run build && npm test
src/index.ts:8:3 - error TS2554: Expected 1 arguments, but got 0.
npm error code 2
npm error command failed
npm error command sh -c npm run build && npm testCommon causes
The build/test invoked by the hook failed
prepare/prepublishOnly typically chain build/test. Any non-zero exit there fails the lifecycle - npm is just relaying it.
prepare runs in an unexpected context
Because prepare also runs on plain installs (including for git dependencies), a hook that assumes devDependencies or a full toolchain can fail when run in a leaner install.
How to fix it
Reproduce and fix the underlying command
Run the hook’s command directly to iterate, then fix the real error.
# run what the hook runs:
npm run build && npm test
# fix the failing build/test, then publish again
npm publishScope the hook correctly
- Put publish-only gates (full build + test) in
prepublishOnly, notprepare, so plain/git installs do not run them. - Ensure the tools the hook needs are present in the install context it runs in.
- Keep the hook’s output visible in CI so the real failure is easy to find.
How to prevent it
- Use prepublishOnly for release-only gates; keep prepare lean.
- Make hook commands reproducible outside CI.
- Ensure required tools exist in the hook’s install context.