Playing with Angular Environments

Reading Time: 6 minutes

Hi! I welcome you abroad the train of “Angular Environments“. Together we are going to have some fun and learn a lot of things. Things you will be covering in this post –

  • Explore the default environments the Angular CLI generates
  • Editing the environments
  • Creating our own environments

Station Zero

Every angular developer have come across many environments to configure there app with and before angular 5 it was a nightmare to set those configs that only should be run in a specific environment. Earlier this process was time consuming and hectic none the less. But with every new release angular community has dissolved the complexity of this problem. Now, setting up the environment configs is matter of only 10 mins, thanks to Angular CLI.

Setting Angular environments

I am assuming that you already have angular installed and npm setup on your system. If not then please follow this link –

Let’s start the train engine!

As of now Angular 9 is the official version. Therefore we will be creating an angular 9 project and I will walk you through how to set up the environment configs in the project. Every application will probably use at least two environments i.e local (aka development) and production. But larger applications may have several environments like QA, pre-prod, staging, etc.

In our DEMO app, we will have three environments : local (aka development), staging (aka QA) and production.

Run the below command in your terminal and create a new angular project or you can download the whole project from my Github!

ng new yourAngularApp

Go to src/environments and you will see two files there : –

  1. environment.prod.ts
  2. environment.ts
env files in the project directory

What are these two environment files that the CLI generates with every new project?

An environment file in the angular application is a JSON configuration information file that tells the build system which files to change for which environment when you use ng build and ng serve.

  • environment.prod.ts is the configuration file that the CLI injects for us when the app is built using the production configuration
  • environment.ts is the configuration default file we reference in our application, and the CLI will take care of getting the correct configuration at build time.

Imagine you have a back-end REST API deployed on a server that provides services to your Angular app. At local, the service URL will be different from that on staging or that on the production. Then, you might be juggling through the app again and again so that it can be used in different environments. Here, you can just define the URL of the service to each of the app environments files and see the magic happen.

Let’s play with code now

Edit environment.ts file with the following code –

export const environment = {
production: false,
name: 'local',
};

Edit environment.prod.ts file with the following code –

export const environment = {
production: true,
name: 'production',
};

NOTE: Remember never put any sensitive information in these environment files.

Edit app.component.ts file with following code –

import {Component} from '@angular/core';
import {environment} from "../environments/environment";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'yourAngularApp';
envName = environment.name;
}

Now hit this command next –

ng serve --open
Check localhost:4200 on your browser

I have refactored the app.component.html file to my liking, you can do that too. It’s up to you, how you do it, so go ahead and use your brain a little 😀 or you can just use mine from the gitHub repo.

Now, kill the serve command wherever you have run it. And run this now –

ng serve --configuration=production --open

or

ng s -c=production --open
Check localhost:4200 in your browser

Do you see the change? How this happened? Do you want to see the actual gears being shifted by angular? Ok! ok! hold your horses!

Let’s dig deeper

Open up the angular.json file

angular.json

Under the architect, you can see 6 different key-value pairs. Each value defines the config to be used in that specific key and configs can be passed down from keys to keys. Each key also represents the angular CLI command like serve represents the ng serve command, build represents the ng build command, and so on. When you hit ng build command in your terminal all the configs defined inside the value of build key will be triggered or you can say will be used.

Open up build key, inside it you will see the configurations key and inside this, you will see the fileReplacements array,

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

Bullseye! You now know what’s happening! Whenever we are hitting the command to serve the application, the environment.ts file is getting replaced with environment.prod.ts file. But I entered a serve command rather than this build command, so how come this build value is being triggered?

OK! Nice, you are curious and attentive. The answer lies within the angular.json file only. Begin DIGGING!

Open up the serve key now, look for configurations

"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "yourAngularApp:build"
},
"configurations": {
"production": {
"browserTarget": "yourAngularApp:build:production"
}
}
},

Voila! You can see that it’s referencing the build key in the value. It’s telling that if we use ng serve –configuration=production command, it will trigger the build -> production values and that’s how we are able to serve the production environment file.

Ok! let’s take a deep breath and recap what we have gathered so far!

  • Every angular project comes with two environment files environment.ts and environment.prod.ts
  • Each environment tells the information to be used in the specific environment to the angular build system.
  • Swapping of these files, which to use with which is defined in the angular.json
  • ng serve uses build values, that’s how it knows which config to use when specified by the user.

I hope you have gathered some insights into this.

Creating our own environment file

Go to src/environemts directory and create a new file

environment.staging.ts

Edit the file with this –

export const environment = {
  production: false,
  name: 'staging',
};

Now edit the angular.json. Add this configuration to the configurations key, parallel with production key

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

Similarly add the following code to the serve key configurations

"configurations": {
"production": {
"browserTarget": "yourAngularApp:build:production"
},
"staging": {
"browserTarget": "yourAngularApp:build:staging"
}
}

And now we can serve our application using the staging environment

ng serve --configuration=staging --open

or

ng s -c=staging --open
Check the localhost:4200 on your browser

Now we have a solid understanding of angular environment files and how to use them to our advantage.

Takeaways

  • Setting up the multi-environment with angular CLI is pretty easy and powerful.
  • Adding configuration information at build time is powerful, but never add any sensitive information.

That’s all for now folks. The train has stopped at a station and we will be departing from this station soon with a new problem ahead of us! I hope you have learned something from this blog. If you liked it then please hit the thumbs up and share it with your friends, family or colleagues. Also, please help me improve by giving healthy feedback (below comments). Follow me to get updates on more interesting blogs.

Visit Knoldus blogs for more angular related topics.

This image has an empty alt attribute; its file name is blog-footer.jpg

Written by 

Shubhrank Rastogi is a FrontEnd Software Consultant at Knoldus Software LLP. He has done MCA from BVICAM, Paschim Vihar, New Delhi. He has a decent knowledge of Web Technologies like JS, TS, Angular, and currently exploring the Ionic framework and React library. He is also a die-hard fan of futuristic gadgets and a tech-savvy person who has a good appetite for delicious food.