Developing Ionic 2.x Apps you certainly face the need to use an external configuration file, and/or several files for different configuration values for different environments. For example, different backend API URLs for development and production. It’s a common topic on Ionic and Angular forums:

Reading configuration files before the application starts

The best pratice we’ve found use the Angular const APP_INITIALIZER to read configuration files before App start. Our approach is inspired by Reading data before application startup in Angular 2:

  • Create env and config files
  • Create ./src/app/config/app.config.ts to load files
  • Update app.module.ts, use APP_INITIALIZER to call init function
  • Create or update copy.config.js in your ./config dir
  • Edit package.json to overwrite ionic_copy
  • Call config in any Angular2 class

Config files

  • Create env file ./src/app/config/env.json setting env key.
{
    "env": "development"
}
  • Create config file ./src/app/config/config.<ENV>.json (ie. /config.development.json)
{
    "api": {
        "host": "localhost"
    }
}

Service to load config

./src/app/config/app.config.ts

Update app.module.ts

Open your existing module and add the following two lines to your list of providers an initConfig function.

Copy config files to build dir

If you previously have copied the default @ionic/app-scripts/config/copy.config.js from Ionic update it, adding copyEnvConfig key/value (see below), else copy it to ./config/copy.config.js.

module.exports = {

...

    copyEnvConfig: {
        src: ['/app/config/**/*.json'],
        dest: '/app/config'
    }
}

Edit package.json to overwrite ionic_copy

And edit the package.json to consider your own copy script instead of ionic one.

{
	"name": "my-app",
	"version": "0.0.1",
	...
	
	"config": {
		"ionic_copy": "./config/copy.config.js"
	},
	
	...
}

In Any Angular2 class

And finally to get config values on any Angular class, import app.config.ts and enjoy it!

import { AppConfig } from '../../app/config/app.config';

export class NewsPage {

    constructor(private config: AppConfig) {}
    
    myMethodToGetHost() {
        // will print 'localhost'
        let host:string = config.get('api.host');
    }
    
    myMethodToGetCurrentEnv() {
        // will print 'development'
        let env: string = config.getEnv('env');
    }
}

Furthermore

If you prefer a smaller and straight forward solution I recommend this solution. Less job for smaller project.

Another solid way use Webpack’s built in EnvironmentPlugin to expose Ionic’s IONIC_ENV environment variable to our code, see roblouie post here. By this way the env vars are loaded on build, different of loading them on App start.


Victor Dias

Sharing mobile Experiences

Follow me