为npm测试运行多个命令

Rem*_*ing 15 node.js npm

我目前正在使用gulp任务来测试项目.这使用以下工具运行任务:

  • 业力(异步)
  • 量角器(衍生过程)
  • ESlint(使用gulp-eslint)
  • HTMLHint(使用gulp-htmlhint)
  • Stylelint(使用gulp-postcss)

如果任何这些任务失败,任务将失败.

所有这些工具都具有完美的cli接口.所以我决定使用npm测试脚本来运行这些工具.

简单地说,只需在没有任何标志的情况下调用它们就可以运行所有工具.然后可以使用以下方法完成:

{
  ...
  "scripts": {
    "test": "karma && protractor && eslint && htmlhint && stylelint"
  },
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,这意味着如果karma失败,其他任何工具都不会运行.

是否可以创建一个所有这些工具都可以运行的设置,但是npm test如果任何命令失败都会失败?

bol*_*lav 13

脚本标记package.json由shell运行,因此您可以运行希望shell运行的命令:

"scripts": {
  "test": "karma ; protractor ; eslint ; htmlhint ; stylelint"
},
Run Code Online (Sandbox Code Playgroud)

如果你有一个unix/OSX shell,将运行所有命令.

为了能够像你指定的那样保留exit_code,你需要有一个单独的脚本来运行命令.也许是这样的:

#!/bin/bash

EXIT_STATUS=0

function check_command {
    "$@"
    local STATUS=$?
    if [ $STATUS -ne 0 ]; then
        echo "error with $1 ($STATUS)" >&2
        EXIT_STATUS=$STATUS
    fi
}

check_command karma
check_command protractor
check_command eslint
check_command htmlhint
check_command stylelint
exit $EXIT_STATUS
Run Code Online (Sandbox Code Playgroud)

  • 请注意,第一个示例中的`test`脚本不支持Windows,PowerShell中的`;`语法无效. (2认同)

Chr*_*ris 8

npm-run-all也可以很好地处理这个问题

您可以同时运行多个npm命令,继续出现错误,如下所示:

npm-run-all --parallel --continue-on-error karma protractor eslint htmlhint stylelint

文档中写的选项:

-p, --parallel <tasks>   - Run a group of tasks in parallel.
                           e.g. 'npm-run-all -p foo bar' is similar to
                                'npm run foo & npm run bar'.
-c, --continue-on-error  - Set the flag to continue executing other tasks
                           even if a task threw an error. 'run-p' itself
                           will exit with non-zero code if one or more tasks
                           threw error(s).
Run Code Online (Sandbox Code Playgroud)

  • 我现在实际上同时喜欢这个. (3认同)

Rem*_*ing 7

并发是一个很好的库,可以处理这个问题.它可以从npm安装.

npm install --save-dev concurrently
Run Code Online (Sandbox Code Playgroud)

当每个部分作为单独的脚本排序时,脚本部分package.json看起来有点像这样:

{
  ...
  "scripts": {
    "test": "concurrently 'npm run karma' 'npm run protractor' 'npm run eslint' 'npm run htmlhint' 'npm run stylelint'",
    "karma": "karma start --single-run",
    "protractor": "protractor",
    "eslint": "eslint .",
    "htmlhint": "htmlhint 'app/**/*.html'",
    "stylelint": "stylelint 'app/**/*.css'",
  },
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • ````test':"同时'npm运行业力''npm运行量角器''npm运行eslint''npm运行htmlhint''npm运行stylelint'"```应该是```"test":"同时\ "npm run karma \"\"npm run protractor \"\"npm run eslint \"\"npm run htmlhint \"\"npm run stylelint \""```on windows. (2认同)