【问题标题】:npm script pass parameters/arguments to node script using yargsnpm 脚本使用 yargs 将参数/参数传递给节点脚本
【发布时间】:2017-12-13 16:32:27
【问题描述】:

作为 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:
{ _: [], '$0': 'scaffold/index.js' }
undefined

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

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

我错过了什么?

2017 年 11 月 7 日更新 相关:Sending command line arguments to npm script

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

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

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


2017 年 7 月 13 日更新

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

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

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


2017 年 7 月 18 日更新

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


2017 年 7 月 24 日更新

在命令开始之前添加变量有效 myvar="hello npm run scaffold 而不是 npm run scaffold myvar="hello world"

【问题讨论】:

    标签: javascript npm yargs


    【解决方案1】:

    对我来说,以下适用于节点 10、12、14

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

    我确实需要使用-- --

    "yourscript": "node bla.js"
    

    【讨论】:

    • 节点 16 (npm 8.3) 仍然存在此问题。仅针对所有这些愚蠢的脚本问题,我总是使用 yarn 而不是 npm
    【解决方案2】:

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

    //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 脚本命令前加上你的参数列表。

    【讨论】:

    • 非常有趣。将变量添加到命令的开头是可行的。最后,它失败了。谢谢你的回答
    • 很高兴你知道了。只是将一个新分支推送到您的示例存储库,其中包含更改并且 github 不合作。
    【解决方案3】:

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

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

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

    【讨论】:

    • 这个答案不完整。我去过这个页面,读了,又读了好几次。您复制并粘贴的示例。在我的示例中,如果我 console.log 你的process.argv,我仍然看不到在你的回答中检索 process.argv 上的name 属性的方法,也看不到你的grepargument例子。
    • 如果您可以使用您的代码(package.json、index.js 等)创建一个公共 GitHub 存储库,我可以尝试调试它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2015-02-25
    • 2015-05-13
    • 2019-02-08
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多