将参数传递给 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.您应该像 Git Bash 一样在 Windows 上使用 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"
}
或者使用工具 scripty 并将您的脚本放在一个单独的文件中.
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屋!