Best practice for upgrading npm `prepublish` script for npm@>=4

Viewed 3263

I run npm install from my sample project's root folder to build it using scripts in package.json.

The build requires a few transpilation steps currently in the prepublish script, but npm version 4 displays a warning that a breaking change is coming, leading me to believe the new prepare build event script is more future proof.

C:\code\antlr4ts-json>npm install
npm WARN prepublish-on-install As of npm@5, `prepublish` scripts will run only for `npm publish`.
npm WARN prepublish-on-install (In npm@4 and previous versions, it also runs for `npm install`.)
npm WARN prepublish-on-install See the deprecation note in `npm help scripts` for more information.
...

Unfortunately, simply moving the script from prepublish to prepare breaks backward compatibility: If someone runs npm install using npm@3, the build steps in prepare are silently ignored.

What's the best practice for upgrading my build-time script? Ideally, I'd like to update my package.json so that npm install works for any npm@>=3, but alternatively generating a clear error message indicating that npm@>=4 is required at when npm install is run using npm@3 would be perfectly acceptable.

Bakground: I tried including

"engines": { "npm":  ">=4.0.0" },

Thanks to @toomuchdesign (and others), I understand why this doesn't do what I want; engines only checks when my package is installed as a dependency, not someone builds it from sources. That makes sense.

I tracked the background on this planned change down to npm issue #10074, which explains why a breaking change is needed. However I'm still unclear how to handle the transition better.

2 Answers
Related