【问题标题】:node: accessing command line arguments from npm scripts and using them from scripts节点:从 npm 脚本访问命令行参数并从脚本中使用它们
【发布时间】:2019-09-09 05:52:14
【问题描述】:

我想在我的 package.json 中定义以下脚本

scripts: {
  "filter": "npm run jest -- -t $1",
  "jest": "jest",
  [...]

想法是我可以运行npm run filter -- my-filter来执行npm run jest -- -t my-filter

如果我跑:

npm run filter -- pattern
-->
npm run jest -- -t $1 "pattern"

$1 是字面的。如果我在脚本中取消 $1 ,它可以正常工作,看起来 npm 在句末传递了所有参数。我只想知道如何使用单个参数

【问题讨论】:

    标签: node.js npm npm-scripts


    【解决方案1】:

    你可以这样做。

    npm run <command> [-- <args>]
    

    例如:-

    "scripts": {
        "server": "node server.js"
    }
    

    那么下面的命令是等价的:

    node server.js --port=1337 => npm run server -- --port=1337
    

    另一个简单示例,

    {
      "print": "f(){ echo Hello $1! && echo Bye $2! ;};f",
      "test": "npm run print -- world stranger"
    }
    

    你得到:

    $ npm test -s # -s is to suppress npm messages for this example
    Hello world!
    Bye stranger!
    

    希望这段代码可以帮助您理解和解决您的问题。

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2020-09-30
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 2018-03-29
      相关资源
      最近更新 更多