node.js 将参数传递给 package.json 中的 npm 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35221098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:51:58  来源:igfitidea点击:

Passing arguments to npm script in package.json

node.jsparametersnpmarguments

提问by EnZo

Is there a way to pass arguments inside of the package.json command?

有没有办法在 package.json 命令中传递参数?

My script:

我的脚本:

"scripts": {
  "test": "node mytest.js   | node_modules/tap-difflet/bin/tap-difflet"
}

cli npm run test 8080 production

命令行 npm run test 8080 production

Then on mytest.jsI'd like to get the arguments with process.argv

然后mytest.js我想得到参数process.argv

回答by aleung

Note: It only works on shell environment, not on Windows cmd. You should use bash on Windows like Git Bash. Or try Linux subsystem if you're using win10.

注意:它只适用于 shell 环境,不适用于 Windows cmd。您应该像 Git Bash 一样在 Windows 上使用 bash。或者,如果您使用的是 win10,请尝试 Linux 子系统。

Passing arguments to script

将参数传递给脚本

To pass arguments to npm script, you should provide them after --for safety.

要将参数传递给npm script--为了安全起见,您应该在之后提供它们。

In your case, --can be omitted. They behaves the same:

在你的情况下,--可以省略。它们的行为相同:

npm run test -- 8080 production
npm run test 8080 production

But when the arguments contain option(s) (e.g. -p), --is necessary otherwise npm will parse them and treat them as npm's option.

但是当参数包含选项(例如-p)时,--是必要的,否则 npm 将解析它们并将它们视为 npm 的选项。

npm run test -- 8080 -p

Use positional parameters

使用位置参数

The arguments are just appended to the script to be run. Your $1$2won't be resolved. The command that npm actually runs is:

参数只是附加到要运行的脚本。你的$1$2不会得到解决。npm 实际运行的命令是:

node mytest.js   | node_modules/tap-difflet/bin/tap-difflet "8080" "production"

In order to make position variable works in npm script, wrap the command inside a shell function:

为了使位置变量在 npm 脚本中起作用,请将命令包装在 shell 函数中:

"scripts": {
  "test": "run(){ node mytest.js   | node_modules/tap-difflet/bin/tap-difflet; }; run"
}

Or use the tool scriptyand put your script in an individual file.

或者使用工具指令码,并把你的脚本在一个单独的文件。

package.json:

包.json:

"scripts": {
  "test": "scripty"
}

scripts/test:

脚本/测试

#!/usr/bin/env sh
node mytest.js   | node_modules/tap-difflet/bin/tap-difflet