将其包装到shell函数中应该可以做到以下几点:
"test": "f() { if [ $# -eq 0 ]; then mocha './test/**/*.test.js'; else mocha -- \"$@\"; fi; }; f"
注意,我稍微更改了if条件和else分支,以便在必要时可以指定多个文件参数。
更简洁的方法:
"test": "f() { mocha -- \"${@:-./test/**/*.test.js}\"; }; f"
git aliases
.
详细说明
"scripts": {
"myscript": "if [ \"$1\" = one ]; then printf %s\\\\n \"$@\"; else echo false; fi"
}
这里,如果第一个参数是“one”,则打印所有参数,否则打印“false”。我们当然是假设
npm run-script
正在使用类似sh的shell,而不是,例如,Windows的cmd.exe。
npm documentation
具体细节
怎样
参数被传递给脚本,所以让我们看一下源代码(在编写时是npmv6.14.7)。这个脚本似乎和它的论点连在一起了
here
here
. 基本上,
npm run myscript -- one two three
sh -c 'if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi "one" "two" "three"'
我们的论点
one two three
fi
.
sh
金融机构
只是一个注定的结局
if
不需要争论。
sh -c 'if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi' sh "one" "two" "three"
在这里
one
,
two
three
是sh本身的参数,因此成为参数变量
$1
,
$2
$3
在给定的脚本中。npm不允许我们直接这样做,但我们可以通过将脚本包装到shell函数中来完成同样的任务:
"scripts": {
"myscript": "f() { if [ \"$1\" = one ]; then printf %s\\\\n \"$@\"; else echo false; fi; }; f"
}
这里的脚本以对函数的调用结束,因此npm将把参数连接到这个调用,最终调用函数
f "one" "two" "three"
:
sh -c 'f() { if [ "$1" = one ]; then printf %s\\n "$@"; else echo false; fi; }; f "one" "two" "three"'