How can I pass an npm param to angular.json

1.5k Views Asked by At

I'm a newbie in angular trying to pass a parameter to my angular build process.

I want to build my app for a specific client so I'm using npm variables to copy the client settings:

npm run build --client=cocacola

However, I cannot figure out how to pass my client name (e.g: cocacola) to my angular.js

This is my scripts in package.json

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "prebuild": "cp src/app/clients/$npm_config_client.settings.ts src/app/app.settings.ts",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

This is part of my angular.json

"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
    "outputPath": "dist",
    "index": "src/index.html",
    "main": "src/main.ts",
    "polyfills": "src/polyfills.ts",
    "tsConfig": "src/tsconfig.app.json",
    "assets": [
      "src/favicon.ico",
      "src/assets",
      {"glob": "**/*", "input" : "src/$npm_config_client/assets", "output": "/assets/"}
    ],
    "styles": [
      "src/styles.scss"
    ],
    "scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/popper.js/dist/umd/popper.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ]
  },

Where I'm trying to use my --client in options/assets to load specific client assets.

{"glob": "**/*", "input" : "src/$npm_config_client/assets", "output": "/assets/"}

Is it possible to do this in Angular?

I also created one angular.json per each client but there has to be a better way.

2

There are 2 best solutions below

0
On

Have you tried to use "configuration"?

Like this:

"configurations": {
"cocacola": {
          "assets": [{"glob": "**/*", "input" : "src/cocacola/assets", "output": "/assets/"}],
        }}
4
On

I'd suggest you want to actually build multiple projects, so:

angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
      "main":{
         "architect": {
            "build": {
               ... standard build configuration
            }
         }
      }
      "cocacola":{
         "architect": {
            "build": {
               ... add cocacola wherever you need here
            }
         }

      }
   }
   "defaultProject": "main"
}

you can then turn this option on or off using the project option of the angular command, so:

package.json:

"scripts": {
    "build": "ng build",
    "build:cocacola": "ng build cocacola"
}

npm run build:cocacola will now run the cocacola project and npm run build runs the none cocacola option.