Gulp + Environment Variables Setup

I’m deciding to make a blog post because, like most things node, there’s just a plethora of options out there and I wanted something minimal and clean. Clean such that I’m taking an asynchronous task runner and making it synchronous by the only means necessary:

gulp.task('two', ['one'], function() {
  // task 'one' is done now
});

Here’s the basic formula
* One separate config file that has attributes specific to each environment (dev, stage, prod).
* Specify the target environment in my gulp command (ie, gulp –env dev).
* Simple string replace mechanism. I’ve noticed the convention of using ‘@@varName‘ which I will use here.
* Keep the variables in my ES6 js files and compile to my build directory.

Config file: environment-config.json

{
    "apiUrl" : {
      "dev": "https://dev-api-url",
      "stage": "https://stage-api-url",
      "prod": "https://prod-api-url"
    }
}

In gulpfile.js

var replace = require('gulp-replace'); // Simple string or regex replacements
var argv = require('yargs').argv; // The contemporary library of choice for parsing command arguments (in this case flags)
var fs = require('fs'); // Read a file

gulp.task('replace', ['babel'], function() {
  var settings = JSON.parse(fs.readFileSync('environment-config.json', 'utf8'));
  var env = argv.env;
  var targetApiUrl = settings.apiUrl[env] ? settings.apiUrl[env] : settings.apiUrl['prod'];
  if (targetApiUrl) {
    gulp.src(['./www/js/app.js'])
      .pipe(replace('@@apiUrl', targetApiUrl))
      .pipe(gulp.dest(function(file) {
        return file.base;
      }))
  }
});

In this case, ‘babel’ is copying over my ES6 to my build directory along with the environment variables, when that is done, my ‘replace’ task is parsing my environment-config.json and reading the environment variables. I’m then targeting my build files (in this case, I’m only targeting app.js which is where most configuration should go for an Angular project), running my replace, and then performing a workaround that allows me to build to the same destination as my source file. Most of the tutorials I’ve seen has neglected to account for modularization of gulp tasks and assume that the source will compile to the destination and you’re done. By compiling to the same file, you’re not interfering with the other asynchronous gulp tasks that may alter the same file. Other tutorials have also asked to create a file for each environment which I think is kind of silly and overkill.