如何检查 npm 脚本是否存在?
How to check if npm script exists?
我正在创建一个 bash 脚本,它 运行 贯穿我的每个项目,如果 test
脚本存在,则 运行 贯穿 npm run test
。
我知道如果我进入一个项目并且 运行 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
但是,我不知道如何获取该信息,看看 test
是否可用,然后 运行 它。
这是我当前的代码:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "[=11=]")" && 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"
编辑:
正如 Marie 和 James 所提到的,如果您只想 运行 命令(如果存在),npm 有一个选项:
npm run test --if-present
这样您就可以拥有一个适用于多个项目(可能有也可能没有特定任务)的通用脚本,而没有收到错误的风险。
来源:https://docs.npmjs.com/cli/run-script
编辑
您可以执行 grep 来检查单词 test:
npm run | grep -q test
如果 npm 运行 中的结果包含单词 test
,则此 return 为真
在你的脚本中它看起来像这样:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "[=12=]")" && 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"
如果test这个词是另外一个意思,那就麻烦了
希望对你有帮助
正确的解决方案是使用 if-present 标志:
npm run test --if-present
我正在创建一个 bash 脚本,它 运行 贯穿我的每个项目,如果 test
脚本存在,则 运行 贯穿 npm run test
。
我知道如果我进入一个项目并且 运行 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
但是,我不知道如何获取该信息,看看 test
是否可用,然后 运行 它。
这是我当前的代码:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "[=11=]")" && 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"
编辑: 正如 Marie 和 James 所提到的,如果您只想 运行 命令(如果存在),npm 有一个选项:
npm run test --if-present
这样您就可以拥有一个适用于多个项目(可能有也可能没有特定任务)的通用脚本,而没有收到错误的风险。
来源:https://docs.npmjs.com/cli/run-script
编辑
您可以执行 grep 来检查单词 test:
npm run | grep -q test
如果 npm 运行 中的结果包含单词 test
,则此 return 为真在你的脚本中它看起来像这样:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "[=12=]")" && 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"
如果test这个词是另外一个意思,那就麻烦了 希望对你有帮助
正确的解决方案是使用 if-present 标志:
npm run test --if-present