Angular 2 and environment variables

Ivan Radunović
Jan 18, 2017 · 2 min read

For all my Angular 2 apps I am using angular-cli, for some time I was developing without it, but when I discovered what options if offers I forgot everything else.

One of those options is handling different environments. Everyone needs to manage at least 2 environments, one development which uses that localhost:4200 and other for production.

Env files

environment.ts is default environment, when you don’t specify — env value that file variables are used.

Content of default file:

export const environment = {
production: false,
apiUrl: 'http://example.com/api/',
};

Properties specified here will be available for type hinting throughout entire application.

Consuming environment variables

import { environment } from '../../environments/environment';

And now I can use them in my classes as any other object:

apiUrl = environment.apiUrl;

Angular command line tool knows which file to use for each environment no matter we imported default env file in our classes.

Building project

~prompt$ ng build

Without any options above command will use default env file. For production environment:

~prompt$ ng build --env=prod

This is good now we are built system with production variables, but angular-cli offers one more option:

~prompt$ ng build --prod --env=prod

This prod option will minify all files and do all other sorts of cool things which are not so important right now. It is good to mention that one of my builds went from 7MB to 2.3MB when I used this option.

Happy building!

Beautiful Angular

Angular simplifies development and brings joy to web…