为 npm@>=4 升级 npm `prepublish` 脚本的最佳实践

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

我从 my sample project's 根文件夹 运行 npm install 使用 package.json 中的脚本构建它。

目前在 prepublish 脚本中构建需要几个转译步骤,但 npm 版本 4 显示警告,即将发生重大变化,让我相信新的 prepare 构建事件脚本更有前途。

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.
...

不幸的是,简单地将脚本从 prepublish 移动到 prepare 会破坏向后兼容性:如果有人 运行s npm install 使用 npm@3, prepare 中的构建步骤被忽略。

升级我的构建时脚本的最佳做法是什么?理想情况下,我想更新我的 package.json 以便 npm install 适用于任何 npm@>=3,但会生成一条明确的错误消息,指示 npm@>=4npm install 时是必需的运行 使用 npm@3 是完全可以接受的。

背景:我试过包括

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

感谢@toomuchdesign(和其他人),我明白了为什么这不符合我的要求; engines 只检查我的包何时安装 作为依赖项 ,而不是有人 从源 构建它。有道理。

我追踪到此计划更改的背景 npm issue #10074,这解释了为什么需要进行重大更改。但是我仍然不清楚如何更好地处理过渡。

NPM docs 指出 engines 字段仅在您的包作为依赖项安装时才会抛出错误:

Unless the user has set the engine-strict config flag, [engines] field is advisory only will produce warnings when your package is installed as a dependency.

作为项目的 developer/mantainer,您应该看不到来自 engines 字段的任何警报。

因为你只需要在 运行 npm install 时编译你的文件,你可以简单地使用 postinstall 钩子。

另请注意,prepublish 会保留下来,它只会通过仅在 publish 钩子之前触发来改变其在 npm@5 上的行为。

我使用 check-node-version 找到了更好的解决方案;该软件包有一个命令行界面,可以很容易地用于此目的。以下是我建议的最佳实践步骤:

  1. 添加开发依赖 npm install -D check-node-version@1,
  2. 将现有的 prepublish 脚本重命名为 prepare,
  3. 添加替换 prepublish 脚本来处理向后兼容性,并建议升级 npm(见下文。)

我的 package.json 现在看起来像这样:

"scripts": {
    "prepare": "npm run antlr4 && tsc",
    "prepublish": "check-node-version --npm \">=4\" || npm run prepare",
    "antlr4": "rimraf gen && antlr4ts Json.g4 -o gen -visitor",
    ...
},
"devDependencies": {
    "check-node-version": "^1.1.2",
    ...

采用这种方法:

  • npm install 总是 运行 是 prepare 脚本,即使安装了 npm@3。如果安装了 npm@5(未经测试),这应该可以正常工作。

  • npm@3上什至有一个关于升级npm的帮助信息,但是因为脚本使用|| npm run prepare来模拟更高版本的行为,所以脚本在错误后继续。

  • 如果我以后想硬依赖 npm@4,如果 运行 在 [=19] 上删除 || npm run prepare 部分会导致脚本停止=].

这是使用 npm@3:

构建的样子
C:\code\antlr4ts-json>npm i

> antlr4ts-json@1.0.6-alpha prepublish C:\code\antlr4ts-json
> check-node-version --npm ">=4" || npm run prepare

node: v6.9.1
npm: v3.10.10
Error: Wanted npm version ">=4" (>=4.0.0)
To install npm, run `npm install -g npm@>=4`

> antlr4ts-json@1.0.6-alpha prepare C:\code\antlr4ts-json
> npm run antlr4 && tsc