New Ionic 3 Environment Support


#1

Hello, I’m trying to configure the new Environment system, although I have configured my own by creating a custom webpack config.

But I want to use the new one, the problem is. It was not clear how the files will be, or how to read the variables from my environment. By read I mean, how to access them in other typescript files (Though the way we read process.env from node.js).

The new system mentioned in: https://github.com/ionic-team/ionic-app-scripts#environments

It says: Create in the root of the app the files .env.dev and .env.prod, but it doesn’t says what is the format(language/syntax) to use in them.

In my current system I have 3 files to configure the environment, all of them are Typescript files.

Within the current system, is it possible to declare a base configuration with all default values such as appVersion, and then create another environment files that override them depending whenever it is dev or prod ?

What is the syntax to use within the .env files ?

Before messing up with the current project I want to understand the new system :grin:.

Many thanks !


#2

See https://github.com/motdotla/dotenv#usage I would guess.


#3

Ok, I have been able to setup the project to the new environment system.
In my project I was fortunately using a Provider for configuration to wrap the environment variables.

First I have created the file to declare the ‘process’ globally (As mentioned in the app-scripts doc):
src/declarations.d.ts <- also this can be “whatever.ts”

declare var process: { env: { [key: string]: string | undefined; } };

I have created an environment model just to document and keep track of all available environment variables along the project.

model/environment.ts

export class Environment {
    version: string = process.env.VERSION || '0.1.26';
    mode: string = process.env.MODE;
    apiBaseUrl: string = process.env.API_BASE_URL;
    updateUrl: string = process.env.UPDATE_URL;
    apkDownloadUrl: string = process.env.APK_DOWNLOAD_URL;

    constructor(){

    }
}

As also said in official documentation the process.env.* will be replaced with the proper declared variables within the right declarations found on default process.env, .env.dev or .env.prod.

So I have created at the root of project as also said in official documentation, the .env.dev and .env.prod with the format mentioned by @Sujan12 :slight_smile: :

.env.dev

API_BASE_URL=http://whatever.thing/

In the AppConfigProvider I provide a singleton instance of the Environment when requested from another module.

With this approach I have been able to define default values for my env variables and also document them.

Thanks !


#4

Just to clarify are you able to build for prod with the --prod flag? Dev works fine for me but prod does not pass in any of the variables from my .env.prod file. Instead they are just undefined.


#5

The same to me. Have you found a solution for this problem? Thank you in advance!