angulartypescriptenvironment-variablesangular-clibuild-tools

Is there a way to pass arguments by CLI when building an Angular application?


I'm using Angular 16 and I have a specific scenario: My application will run locally in many machines, each one with one different ip, so that means that every server url will be different. Currently, I'm getting this url from the environment.ts, like this:

export const environment = {
    apiUrl: 'http://11.22.33.44:5678/',
};

Currently, every time I need to build the application, I change the url manually. I want to do this by a CLI command. i.e ng build --configuration=production --serverUrl=http://55.66.77.88:5678/.

This is my angular.json production section

"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.development.ts",
        "with": "src/environments/environment.ts"
      }
    ]
}

I have read this question, but it says that I'll need to create one environment for each scenario. It's not fully dynamic.


Solution

  • First, try to set a placeholder value for apiUrl:

    export const environment = {
        apiUrl: 'PLACEHOLDER_VALUE',
    };
    

    Then, when building your project you can use the --env option to specify the apiUrl environment variable value, like:

    ng build --configuration=production --env.apiUrl='YOUR_ACTUAL_API_HERE'