When using the Angular CLI, one of the many benefits you get is how easy it is to use environmental variables in your application.

So what are environmental variables?

If you have ever launched an application or a site for yourself, and later on needed to build some extra features on to it, I bet you have either used or wished for your application to be able to hit another endpoint where you server your data from a development server while building the new feature.

Then when releasing your application you want to use the data from the live server once again when the feature is ready.

This is exactly what environmental variables makes possible, you have one set of variables for your development setup and another for your live environment, maybe even a third for your staging.

Environment files

From the root of your project, you can find a directory for your environment files at “src/enviroments”. environment.ts is the default environment that will be used unless told otherwise to serve your variables.

The content of the default file (environment.ts) is:

export const environment = { production: false };

You can make your own environment called environment.dev.ts or environment.staging.ts or any other you could wish for using the pattern environment.*.ts, that you can later use within your application.

Consuming the environmental variables

Where ever you are in your application you can always import and use a the environmental variables, just remember that if your application relies on them, for example to define an endpoint of a API server, to always have them available in the other environments that you will be using.

You can import the variables by grabbing them from the default file path and use it like this:

import { environment } from '../../environments/environment'; baseUrl: string = environment.baseUrl;

The CLI will make sure to swap the file to whatever environment you have specified when building your application.

Building the application

You have now managed to include and use your environmental variables while developing your new features and it is time to release your app to production, exciting!

The usual “ng build” will use the default environment, which might not be the one you wanted to use for your production application.

Luckily there is an option on the command that we can use, called “–env”. You can use it by simply adding it to your “ng build” command.

ng build –env=prod

This is great because now we can easily swap between environments depending on where we are releasing the app.

You should ofcourse also remember to add the “–prod” option if you indeed are releasing for production.

ng build –prod –env=prod

This will treeshake and minify your application as well as use the AOT compiler if you have not specified it not to, which means your application will be far smaller and faster to load.