DEV Community

Ankit Kumar Sharma
Ankit Kumar Sharma

Posted on • Edited on

How to use multiple Environment Variables in Angular

Image description
In this article, we will learn about different Environment Variables in different files.

First, when we create any angular application, so by default it have two environment files, which one is for dev, and another one is for prod.
But if we need to create more multiple environment files like QA, UAT, PROD, DEV etc and all files, we have different constant variables for API and other values.

Add more custom environment files with different values

For our different requirement, we have to create different files under environment folder like qa, uat, xyz etc.
we can add values as per our requirement.

I have created 3 environment files as per different requirement (dummy). You can create as per your requirement

environment.qa.ts // for QA Testing Part
environment.uat.ts // for UAT Testing Part
environment.xyz.ts // for client demo part

Enter fullscreen mode Exit fullscreen mode

Image description

// we generated this file for UAT Testing Part
export const environment = {
  production: true,
  environmentName: 'UAT',
  apiUrl: 'uat.abc.com',
  paginationSize:'20',
};
Enter fullscreen mode Exit fullscreen mode

Update Config Part on anjular.json file

In each angular project, there is a file angular.json that have config part and setup of project related information, so we have to add new environment files for use in our project
We can add new part under projects/architect/build/configurations

Image description

"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"
 },
 "xyz": {
   "fileReplacements": [
  {
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.xyz.ts"
  }
   ],
   "outputHashing": "all"
 },
Enter fullscreen mode Exit fullscreen mode

Ready Build for a custom environment

when your configuration part is ready, then you can create build for your respective environment as per your requirement by a flag — configuration run with ng build command.
for example.

ng build --configuration uat

GitHub Source Code

when build is ready, then you can publish your files as per respective environment.

Please give your respectve feedback, that will be helpfull for improve my article quality.

https://www.ankitkumarsharma.com/

Also please follow me on GitHub , Twitter , Medium, and Dev for more updates on articles with hands on code queries.

Thanks

Top comments (0)