代码之家  ›  专栏  ›  技术社区  ›  Simon

npm脚本使用yargs将参数/参数传递给节点脚本

  •  19
  • Simon  · 技术社区  · 8 年前

    OSX终端中的用户类型:

    npm run scaffold --name=blah
    

    "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
    

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

    我错过了什么?

    更新11-07-2017 相关: 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 所有物仍未定义。


    更新13-07-2017

    例如。

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

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

    enter image description here


    更新18-07-2017

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


    更新24-07-2017

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

    3 回复  |  直到 8 年前
        1
  •  12
  •   sabrehagen    8 年前

    截至npm@2.0.0,您可以在执行脚本时使用自定义参数。特殊选项--由getopt用于分隔选项的末尾。npm将把--后面的所有参数直接传递给脚本:

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

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

        2
  •  7
  •   Chase    8 年前

    //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    
    

        3
  •  4
  •   BrunoLM    5 年前

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

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

    我确实需要使用 -- --

    "yourscript": "node bla.js"