当经由可执行文件(的.bin)NPM脚本调用传递参数到节点

问题描述 投票:1回答:1

我定义的NPM CLI命令作为mycommand模块:

{
  ...
  "name": "mycommand",
  "bin": {
    "mycommand": "bin/mycommand.js"
  },
  ...
}

其中mycommand.js看起来是这样的:

#!/usr/bin/env node --harmony

console.log('...')

我希望能够通过以下方式,安装在另一个模块运行它:

{
  ..
  "scripts": {
    "mycommand": "mycommand --require ./bootstrap"
  }
  ...      
}

其中bootstrap是,我期望能够requiremycommand-ED的模块。该--require参数应该被传递到节点运行mycommand

结果与尝试

  1. 不幸的是,从来没有要求bootstrap。没有任何错误或不正确的路径解析或类似的其他指示。
  2. 如果我以不同的方式定义mycommand脚本: { ... "scripts": { "mycommand": "node --require ./bootstrap ./some-random-js-file" } ... }

如预期bootstrap是必需的,证明bootstrap存在和--require工作。

  1. 如果我直接requirebootstrap模块mycommand(我真的不能做的 - 所以只是为了测试的缘故): #!/usr/bin/env node --harmony require('../../../bootstrap'); console.log('...')

如预期bootstrap是必需的。需要注意的是../../../有以补偿mycommand.jsnode_modules内的位置。

假设

我认为--require不会真正传递给节点执行mycommand

如何才能做到这一点?

npm command-line-interface yarnpkg npm-scripts
1个回答
1
投票

你的假设--require不会传递到node是正确的:

  • 当您运行node --require … path/to/mycommand.js你传递参数给node
  • 当您运行mycommand --require …你传递参数给mycommand

(你可以根据需要在解析和mycommand.js require()命令行选项,如果适合你的使用情况)

我假设你不想因为你需要指定路径的脚本,从而失去在第一时间创建node … mycommand.js场整点使用bin方法。

然而,由于您提供一个bin场,你就已经有mycommand已知路径:

{
  ..
  "scripts": {
      "mycommand": "node --require ./bootstrap ./node_bin/mycommand"
  }
  ...      
}

或可改为… $(npm bin)/mycommand

© www.soinside.com 2019 - 2024. All rights reserved.