Externalized configuration

I’d like to avoid having to toggle comments my REST service url when switching from development (localhost) to production.

angular.module('foo.services', [])
    .constant('fooServiceConst', {
        // FOOSVC_WEB_PATH: 'http://localhost:3000'})
       FOOSVC_WEB_PATH: 'http://foodomain.com'
    })

What’s the best alternative to this in ionic?

Personally, I use a build tool (grunt) to do this automatically for me.

It was more involved than I expected, so circling back with my solution for reference.

I ended up using gulp-ng-constant to generate a custom constants module for dev or prod, then adding the dev task to gulpStartupTasks to make sure the dev constants are generated during ionic serve, and using a build script to ensure the prod constants are generated before ionic build.

gulpfile.js

var ngConstant = require('gulp-ng-constant');
...
gulp.task('config', function() {
	gulp.src('./config.json')
		.pipe(ngConstant())
		.pipe(gulp.dest("./www/js/"))
});
gulp.task('config-prod', function() {
	gulp.src('./config-prod.json')
		.pipe(ngConstant())
		.pipe(concat('config.js'))
		.pipe(gulp.dest("./www/js/"))
});

config.json

{
	"name": "starter.constants",
	"constants": {
		"API_HOST": "http://localhost:9090"
	}
}

config-prod.json

{
	"name": "starter.constants",
	"constants": {
		"API_HOST": "http://production"
	}
}

Add "gulpStartupTasks": ["config"] to ionic.project.
Add www/js/config.js to .gitignore.
Add <script src="js/config.js"></script> to index.html.
Add 'starter.constants' to the module list in app.js.

Now ionic serve will generate a dev config.js file with an API_HOST constant pointing to localhost:

config.js

angular.module("starter.constants", [])

.constant("API_HOST", "http://localhost:9090")

;

To handle the production build, I use a build script like this:

#!/bin/bash
gulp config-prod
ionic build

That will generate a config.js with the production constants in it before doing a production build.

It’s worth noting that there’s another approach using hooks to find and replace text described here:
http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/

4 Likes