【问题标题】:Pass npm script command line arguments to a specific script inside it将 npm script 命令行参数传递给其中的特定脚本
【发布时间】:2018-05-13 09:05:28
【问题描述】:

我有一个场景,我必须运行三个 npm 脚本才能在我的应用程序中获得一些结果。我将它们组合在一个 npm 脚本中。这是我的package.json

"scripts": {
    "setup": "npm install && npm run some-script && npm install",
    "some-script": "gulp some-other-script"
}

我想做的是从命令行将参数传递给setup 脚本,该脚本将进一步传递给some-script 脚本。

如果我运行npm run script -- --abc=123,参数会添加到脚本末尾,但我想将其传递给特定脚本(在本例中为npm run some-script)。我还尝试像这样重写脚本定义: "setup": "npm install && npm run some-script -- --sample=sample&& npm install" 但没有运气。

我知道 shell 函数(在此处描述:Sending command line arguments to npm script 和此处https://github.com/npm/npm/issues/9627),但我需要一个可以跨平台工作的解决方案。

有没有办法做到这一点?

【问题讨论】:

  • 您好,您知道如何实现这一点吗,我有相同的案例用法;)
  • 问题似乎来自 && 部分脚本

标签: node.js npm gulp


【解决方案1】:

好的,我找到了解决方法。

第一个目标是能够使用一些带参数的脚本,并将其级联到其他脚本的调用:

npm run main -- --arg1 "main": "npm run script1 && npm run script2"

这种方法的问题是级联只能通过在“npm run script1 && npm run script2”行的末尾添加传递给 npm run main 的 arg 来完成。我找不到将它传递给第一个元素的方法:npm run script1

这是我找到的解决方法:

首先你需要在 package.json 中添加:

"config": {
   "arg1": "ARG_VALUE"
},

然后在您的脚本中,您可以像这样将其添加到调用中:

"main": "npm run script_no_arg1 && npm run scrip1 -- --%npm_package_config_arg1% && npm run script2 -- --%npm_package_config_component% && npm run script_no_arg2"

最后,您不需要使用任何 arg 调用它:npm run main 但是您需要在启动脚本之前修改 ARG_VALUE :)

最后一件事:就我而言,我正在调用 gulp 任务:

"cleardown": "rimraf build lib",
"inline-build-templates": "gulp inline-build-templates",
"step1": "npm run cleardown && npm run inline-build-templates -- --%npm_package_config_arg1%",

您可以通过这种方式将参数放入 gulp 任务中:

 gulp.task('inline-build-templates', function() {
   let component = process.argv[3];
   component = component.split('--')[1];
   console.log('RUNNING GULP TASK : inline-build-templates for component ' + component);
   // whatever task gulp
});

希望对你有帮助。

【讨论】:

  • 是的,除了从命令行链中的最后一个脚本之外,似乎无法为任何其他脚本提供参数。您的解决方案接近我想要的,但我不想在每次执行此命令时更改 package.json 中的某些属性。还是谢谢
猜你喜欢
  • 2017-01-12
  • 2020-05-09
  • 1970-01-01
  • 2017-07-18
  • 2018-01-11
  • 2014-03-08
  • 2013-10-22
相关资源
最近更新 更多