Angular 2 and environment variables

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

In Angular 2 under src directory create new one named environments.

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

In my components, services and other classes when I need some env variable I’ll import default env file, like this:

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

Usual way of doing this is with:

~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!