System environment variables in Angular

Clayton Fidelis
3 min readNov 30, 2018

--

Angular already has his own environment system, can configure everything in src/environments/environment.ts and you can create as many environments as you want. The problem is, sometimes you want to use the System Environment variables, for example, some configuration from the server, in this case, this Angular environment will not help.

In this case, you will want to configure a custom angular-builder to extend the default Angular Webpack configuration. In this Webpack configuration, we will load the system environment variables and pass to Angular using webpack.DefinePlugin.

Hands on

Setup

First let’s install the dependencies:

Then we will make some changes to our angular.json file. Look for @angular-devkit/build-angular:browser and replace with @angular-builders/custom-webpack:browser. This will allow us to use a custom webpack config for the build.

Then we add the customWebpackConfig in the builder options. Your code should look like this:

angular.json

After this, we will create a file called extra-webpack.config.js on the project root. In this file, we will add the code to read the environment variables and send it to Angular.

extra-webpack.config.js

At the first line we import webpack, and then from line 5 to line 9, we configure our environment variables. In this case, I’m passing the USERNAME variable from the system and sending it to Angular.

Usage

The next step is to use it inside our Angular application. First, let’s create a file named typings.d.ts, in this file, we will declare the interface of our environment variables:

typings.d.ts

And then, we can finally use this variable inside our application, you just need to call process.env.USERNAME anywhere in your code, for example:

environment.ts

Unfortunately, this will only work for ng build, for ng serve we will need to add another custom angular-builder to our angular.json:

So now it will work with ng build and ng serve. That’s all!

--

--