A Simple Way to Use Environment Variables in Ionic 3

Environment variables enable specific configuration

Valentin Klinghammer
prototype.berlin

--

Problem

We build a lot of apps for our clients. We also build and deploy the backends for most of those apps. The best practice of using four separate servers emerged. That’s quite a headache to keep straight without automation.

Our apps must be configurable to point at each of those servers while still allowing to toggle Ionic’s built-in --prod flag.

An environment variable must switch the following

We also use the environment variable to

  • Decide what log levels to log
  • Decide wether to enable analytics/tracking or not

Solution

What we want to achieve is an interface, similar to Nodejs apps, that works across all Ionic builds and is programmatically accessible within the app.

APP_ENV=development ionic serve -b

Then we can still do this

APP_ENV=production ionic cordova build ios --prod

but also leave the--prod flag out for easier debugging while still using the production URL without touching the code, like so

APP_ENV=production ionic cordova build ios

To achieve that, we will use Ionics configuration to copy a JavaScript file that contains a global variable with the environment info and load that in our index.html.

Implementation

Steps

1. Create env.js files
2. Copy the right env.js file into our build
3. Load env.js file
4. Profit

1. Create env.js files

We start off by creating a new folder src/env.For the four environments we typically use, we would create four subfolders and files that will contain our environment info.

src/env/development/env.js

window.ENV = 'development'

src/env/staging/env.js

window.ENV = 'staging';

src/env/production/env.js

window.ENV = 'production';

src/env/hacking/env.js

window.ENV = 'hacking';

2. Copy the right env.js file into our build

Next we add something at the beginning of Ionics copy config file, you’ll find it here .config/copy.config.js in your project. We also need to adjust the copyIndexContent task to actually copy our file.

3. Load env.js file

This part is almost trivial, we need to load our env.js file in our src/index.html, do it as soon as possible, e.g. right after cordova.js.

4. Profit

So… Now what?

We use a class that provides us with project-wide constants, e.g. URLs. A minimal version of that might look like this.

Now you can access the environment you’re running as well as the URLs

import { C } from '../shared/constants';console.log(C.ENV, C.urls.users);

I hope this helps!

--

--