将参数传递给package.json中的npm脚本 [英] Passing arguments to npm script in package.json
问题描述
是否可以在package.json命令中传递参数?
Is there a way to pass arguments inside of the package.json command?
我的脚本:
"scripts": {
"test": "node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet"
}
cli npm run test 8080 production
然后在mytest.js
上,我想使用process.argv
推荐答案
注意:它仅适用于shell环境,不适用于Windows cmd.您应该在Windows上像Git Bash一样使用bash.或者,如果您使用的是win10,请尝试使用Linux子系统.
要将参数传递给 npm脚本,您应在--
之后为安全.
To pass arguments to npm script, you should provide them after --
for safety.
在您的情况下,可以省略--
.它们的行为相同:
In your case, --
can be omitted. They behaves the same:
npm run test -- 8080 production
npm run test 8080 production
但是当参数包含选项(例如-p
)时,必须使用--
,否则npm将对其进行解析并将其视为npm的选项.
But when the arguments contain option(s) (e.g. -p
), --
is necessary otherwise npm will parse them and treat them as npm's option.
npm run test -- 8080 -p
使用位置参数
参数仅附加到要运行的脚本中.您的$1
$2
无法解决. npm实际运行的命令是:
Use positional parameters
The arguments are just appended to the script to be run. Your $1
$2
won't be resolved. The command that npm actually runs is:
node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet "8080" "production"
为了使位置变量在npm脚本中起作用,请将命令包装在shell函数中:
In order to make position variable works in npm script, wrap the command inside a shell function:
"scripts": {
"test": "run(){ node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet; }; run"
}
或使用工具脚本,然后将脚本放入单个文件中.
Or use the tool scripty and put your script in an individual file.
package.json :
"scripts": {
"test": "scripty"
}
脚本/测试:
#!/usr/bin/env sh
node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet
这篇关于将参数传递给package.json中的npm脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!