如何在package.json脚本之间传递参数

时间:2019-10-18 00:20:53

标签: node.js angular package.json

我正在尝试减少package.json中的脚本重复。如果我可以对脚本进行参数化,那将大有帮助。

如何从脚本中的任意位置访问参数(并将其保留在package.json中,而不是为此创建外部js文件),而不仅仅是让节点将参数附加到行尾? 请注意,在某些情况下,我想多次使用相同的参数。

例如

这是我目前拥有的,并且有效:

{
  "name": "angular-apps",
  "scripts": {
    "start-drt": "ng serve data-review --open",
    "build-drt": "ng lint data-review --type-check && ng build data-review",
    "build-drt-prod": "ng lint data-review --type-check && node replace-nonce data-review && ng build data-review --prod --progress=false && ng test data-review --watch=false --reporters teamcity",
... // etc.
/* There are several more application scripts that aren't listed.
   The only difference is the project name (e.g. `data-review` in this case).
   They all follow the same pattern as the set of scripts above. */

我想要的是这样的东西(这不起作用,因为它试图直接使用$ 1而不是将其用作变量):

{
  "name": "angular-apps",
  "scripts": {
    "start-app": "ng serve $1 --open",
    "build-app": "ng lint $a --type-check && ng build $a",
    "build-app-prod": "ng lint $1 --type-check && node replace-nonce $1 && ng build $1 --prod --progress=false && ng test $1 --watch=false --reporters teamcity",

    "start-drt": "npm run start-app data-review",
    "build-drt": "npm run build-app data-review",
    "build-drt-prod": "npm run build-app-prod data-review",

    "start-sat": "npm run start-app section-analysis",
    "build-sat": "npm run build-app section-analysis",
    "build-sat-prod": "npm run build-app-prod section-analysis",
... // etc. Now I can add more apps and re-use the same scripts for all of them

1 个答案:

答案 0 :(得分:0)

您可以这样做。

// package.json
script: {
     start: "ng serve $*"
 }

然后像这样npm run start analytics_app称其为process.argv