如何检查 npm 脚本是否存在?

the*_*uls 18 bash shell npm npm-run

我正在创建一个 bash 脚本,它运行在我的每个项目中,并npm run testtest脚本存在时运行。

我知道,如果我进入一个项目并运行npm run它,它将为我提供可用脚本列表,如下所示:

Lifecycle scripts included in www:
  start
    node server.js
  test
    mocha --require @babel/register --require dotenv/config --watch-extensions js **/*.test.js

available via `npm run-script`:
  dev
    node -r dotenv/config server.js
  dev:watch
    nodemon -r dotenv/config server.js
  build
    next build
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何获取该信息,查看是否test可用然后运行它。

这是我当前的代码:

#!/bin/bash

ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
BASE_PATH="${ROOT_PATH}/../.."

while read MYAPP; do # reads from a list of projects
  PROJECT="${MYAPP}"
  FOLDER="${BASE_PATH}/${PROJECT}"
  cd "$FOLDER"
  if [ check here if the command exists ]; then
    npm run test
    echo ""
  fi
done < "${ROOT_PATH}/../assets/apps-manifest"
Run Code Online (Sandbox Code Playgroud)

Den*_*nis 26

编辑: 正如 Marie 和 James 所提到的,如果您只想运行命令(如果存在),npm 有一个选项:

npm run test --if-present
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以拥有一个适用于多个项目(可能有也可能没有特定任务)的通用脚本,而不会有收到错误的风险。

来源:https : //docs.npmjs.com/cli/run-script

编辑

您可以使用 grep 来检查单词 test:

npm run | grep -q test
Run Code Online (Sandbox Code Playgroud)

如果 npm run 中的结果包含单词 test,则返回 true

在您的脚本中,它看起来像这样:

#!/bin/bash

ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
BASE_PATH="${ROOT_PATH}/../.."

while read MYAPP; do # reads from a list of projects
  PROJECT="${MYAPP}"
  FOLDER="${BASE_PATH}/${PROJECT}"
  cd "$FOLDER"
  if npm run | grep -q test; then
    npm run test
    echo ""
  fi
done < "${ROOT_PATH}/../assets/apps-manifest"
Run Code Online (Sandbox Code Playgroud)

如果单词 test 在那里有另一种含义,那只是一个问题 希望它有帮助


小智 12

正确的解决方案是使用 if-present 标志:

npm run test --if-present

  • 因此,请在您的回答中澄清这一点。扩展它,使其成为真正出色的答案。 (2认同)