wimnat wimnat - 6 months ago 19
Node.js Question

Combine two json files to give a set of variables to use in Gulp

I have seen lots of posts online about how to use a set of variables defined in a file using a require statement.

I want to know how I can use two files.

For example, in pseudo...

gulp --env=prod

if (env):
defaultConfig = require('./config/default.json')
envConfig = require('./config/prod.json')
config = combine(defaultConfig, envConfig)
else:
config = require('./config/default.json')

// Now i can access everything like so...
console.log(config.name)
console.log(config.minify)


This keeps by config DRY and also means I don't have to create a new file for every environment I have.

I'm new to Gulp but i thought this would be a common requirement however, Google hasn't turned up anything for having defaults merged with env specific settings.

Do i need to write a node module?

Answer

Use yargs to parse command line arguments and extend to combine the two config objects:

var gulp = require('gulp');
var argv = require('yargs').argv;
var extend = require('extend');

var config = extend(
  require('./config/default.json'),
  (argv.env) ? require('./config/' + argv.env + '.json') : {}
);

gulp.task('default', function() {
  console.log(config);
});

Running gulp --env=prod will print the combined config, while simply running gulp will print the default config.