How to use different Environment Variables in Angular 13

Piyush Jain
2 min readFeb 28, 2022
Angular 13 Environment Variable configuration
Source — https://www.elite-corner.com/wp-content/uploads/2020/06/Environment-Variable-Configuration-in-Angular-Application.png

Introduction

In this article we will learn how to use different environments files for different environments.

When we create angular app using cli by default it has 2 environment files one for dev and one for prod.

Sometimes we need to create separate files for different environments e.g. QA, UAT, Staging, Prod etc. when we have separate API URLS for different environment.

Let’s deep dive into this.

Custom environment file

For each target environment, we will create a new environment file under folder environments. For demo, I have created separate environment files for qa and uat environments.

Custom environment settings

You can put your API URL and other settings in custom environment file. For example,

export const environment = {
production: true,
envName: 'UAT',
apiUrl: 'https://uat.endpoint.com'
};

Update angular.json configuration

In your Angular project, you shall find angular.json file. Inside this file, you can add a new section under projects/architect/build section.

Here is an example with uat and qa environments.

"uat": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.uat.ts"
}
],
"outputHashing": "all"
}
"qa": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.qa.ts"
}
],
"outputHashing": "all"
}

Build application for custom environment

Once your configuration is done, you can build your application for targeted environment by specific --configuration parameter to ng build command. For example, to build application in QA mode, run command

ng build --configuration qa

and dist folder shall contains build output with qa configuration. You can publish your website on your target environment now.

Github

If you liked this please give a clap.

Also let us know who you are doing this in your project. Do share if you know any other approach.

Read Next

--

--

Piyush Jain

An avid front-end technologist with 9+ years of web industry experience. Self-motivated professional with broad technical skill-set and very strong attention.