Exploring a way to set an Angular app’s config from a Gulp build.

Versions used below

{
  "angular": "1.4.0",
  "gulp": "3.9.0",
  "gulp-ng-config": "1.2.1",
  "add-stream": "1.0.0",
  "gulp-concat": "2.4.2",
  "buffer-to-vinyl": "1.0.0"
}

What is Angular config?

For the purposes of this post, Angular config is the constants defined on a module.

angular.module('app')
  .constant('name', 'bob')
  .constant('url', 'http://example.org');

Apps typically use those constants in config blocks to turn off debug helpers, set urls, toggle app flags, etc.

angular.module('app').config(function(url, someServiceProvider) {
  someServiceProvider.setUrl(url);
});

Using gulp-ng-config

Given a json file, gulp-ng-config generates JavaScript that defines constants.

var gulpNgConfig = require('gulp-ng-config');

function makeConfig() {
  return gulp.src('./app-config.json')
    .pipe(gulpNgConfig('app.config'));
}

Assuming app-config.json looks like

{
  "name": "bob",
  "url": "http://example.org"
}

gulp-ng-config generates a js file that looks like

angular.module('app.config', [])
.constant('name', "bob")
.constant('url', "http://example.org");

Appending to app js

Use add-stream and gulp-concat to append the generated config to your main app js.

var addStream = require('add-stream');
var concat = require('gulp-concat');

gulp.task('js', function() {
  return gulp.src('./app/js/**/*')
    .pipe(addStream.obj(makeConfig())) // makeConfig is defined a few code blocks up
    .pipe(concat('app.js'))
    .pipe(gulp.dest('...'));
});

Also be sure your app module depends on the config module.

angular.module('app', ['app.config']);

Environment specific config

The second parameter to gulp-ng-config is an options object.

If the environment option is set, gulp-ng-config looks for a top-level property in the json matching that name and uses its value as the config. This is an easy way to have different settings for development, test and production.

function makeConfig() {
  return gulp.src('./app-config.json')
    .pipe(gulpNgConfig('app.config', {
      environment: 'production' // or maybe use process.env.NODE_ENV here
    }));
}

app-config.json

{
  "production": {
    "url": "http://prod.com"
  },
  "development": {
    "url": "http://dev.com"
  }
}

Result:

angular.module('app.config', [])
.constant('url', "http://prod.com");

Without a json file on disk

If your config values come from somewhere other than a file on disk, you can use buffer-to-vinyl to create and stream a vinyl file into gulp-ng-config.

var b2v = require('buffer-to-vinyl');
var gulpNgConfig = require('gulp-ng-config');

function makeConfig() {
  var json = JSON.stringify({
    // your config here
  });

  return b2v.stream(new Buffer(json), 'config.js')
    .pipe(gulpNgConfig('app.config'));
}