如何有条件地 运行 npm 脚本

How to conditionally run npm script

我正在寻找一种跨平台的方式来有条件地运行在我的构建脚本中添加一个步骤。

我有一个昂贵的构建步骤,但是检查是否有必要相对较快。我创建了一个脚本 returns 如果不需要执行构建步骤,则会出现一个非零错误代码。如果检查通过,我如何将我的 npm 脚本写入 运行 构建,但如果构建步骤失败则提供错误?

示例package.json:

"scripts": {
    "schema:build": "npm run schema:rebuild-check && npm run schema:force-build",
    "schema:rebuild-check": "node tools/schema is-rebuild-necessary",
    "schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"
}

上面的问题是,如果不需要重建,我的整个构建都会失败。我不能只用 exitzero 之类的东西吞下退出代码,因为我想知道 schema:force-build 脚本中是否有任何命令失败。

问题源于两件事:

1) 如果 npm 脚本以 non-zero 代码退出,npm 将始终抱怨

2) 需要使用 || 提供 returns 非零的 "else"运算符

工作解决方案:

"schema:build": "node tools/schema is-rebuild-necessary && npm run schema:force-build || echo Skipping schema build",
"schema:force-build": "npm run schema:validate && npm run schema:generate-index && npm run schema:bundle"