npm 脚本使用 yargs 将 parameters/arguments 传递给节点脚本

npm script pass parameters/arguments to node script using yargs

当用作 npm 脚本参数时,是否可以调出从 yargs 检索密钥?

OSX 终端中的用户类型:

npm run scaffold --name=blah

在package.json中执行:

"scaffold" : "node ./scaffold/index.js -- "

这导致

const yargs = require('yargs').argv

if (yargs) {
  console.log(yargs);
  console.log(yargs.name);
  process.exit(1)
}
...
result:
{ _: [], '[=13=]': 'scaffold/index.js' }
undefined

这仅在我在 package.json "scaffold" : "node scaffold/index.js --name=blah" 中进行硬编码时有效,但我需要它是可配置的。

正如我所说,我正在使用 args,因为它似乎可以很容易地按名称检索键(而不是数组)。接受建议。

我错过了什么?

更新 11-07-2017 相关:Sending command line arguments to npm script

但是,传入命令行 1: npm run scaffold name=hello 2: npm run scaffold --name=hello 会产生:

1: { _: [], '[=14=]': 'scaffold/index.js' }
2: { _: [ 'name=hello' ], '[=14=]': 'scaffold/index.js' }

仍然找不到检索 yargs.name 属性 的方法。仍未定义。


2017 年 7 月 13 日更新

暂时放弃了。这似乎是不可能的。我在终端中手动 运行 脚本。 例如

node ./scaffold/index.js --name=blah 

下图显示了直接执行节点脚本,而不是通过 npm 脚本 运行ning。我添加了 https://www.npmjs.com/package/nopt 节点模块以查看它是否有帮助(它没有)。 process.argv.name 在通过 npm 脚本 运行 时仍然未定义。


更新 18-07-2017

添加了 github 示例:https://github.com/sidouglas/Whosebug-node-arguments


更新 24-07-2017

在命令开始之前添加变量有效 myvar="hello npm run scaffold 相对于 npm run scaffold myvar="hello world"

从 npm@2.0.0 开始,您可以在执行脚本时使用自定义参数。特殊选项 -- 由 getopt 使用来分隔选项的结尾。 npm 会将 -- 之后的所有参数直接传递给您的脚本:

npm run test -- --grep="pattern"

https://docs.npmjs.com/cli/run-script

我不确定在命令行中添加变量的位置是否重要,如果您不关心这个,那么这个可行:

//package.json
{
  "name": "npm-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "scripts": {
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC"
}    

你的 JS 文件:

//index.js
console.log('myvar', process.env.myvar);    

还有你的命令行命令:

myvar="hello world" npm run start    

所以最后,只需在您的 npm 脚本命令前加上您的参数列表。

对我来说,以下在节点 10、12、14 上工作

npm run yourscript -- -- --name=bla

我确实需要使用 -- --

"yourscript": "node bla.js"