Beautiful Angular
Published in

Beautiful Angular

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:

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:

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

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:

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

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

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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store