angular-cli with env vars : WebPack to the rescue

We were wondering how could we get the environment variables up and running without having to re-write the angular-cli’s environment files as described in a lot of posts.

I found this angular-cli issue that seems to be the fix that would help get that done, but we really need it asap.

I’ve found that WebPack, which is now used by angular-cli, has a plugin that can define global constants very easily. But for this, you need to be able to access the webpack.config.js. There is a very useful command that angular-cli implemented: ng eject (official wiki here)

NOTE: This command change all the package.json’s script to use the WebPack calls directly.

Once you have that, you only have to configure the plugin as follow:

...
// Import it
const DefinePlugin = require('webpack/lib/DefinePlugin');
...
"plugin":[
...
new DefinePlugin({
MY_ENV_VAR: JSON.stringify(process.env.MY_ENV_VAR)
})
]
...

Then, from your angular-cli’s environment file

declare var MY_ENV_VAR: any;
console.log(`my env var value is: ${MY_ENV_VAR}`);

All that you now have to do to define it is to actually define the env var when the project compiles. Here is how you would do it locally:

MY_ENV_VAR='from command line!' npm run start

Then running your app, you will get this output:

my env var value is: from command line!

Docker

The cool part with that, is that we can now simply set an env var in our Dockerfile and it the app will be built using it.