How to keep your Gulp configuration options in a JSON file

Changing paths and task options can be cumbersome and confusing as a project gets larger. By keeping all your options and paths in a separate config file it can make the project easier to maintain.

I’ve recently started to switch from Grunt to Gulp and with that switch I’ve learned a lot of new things and re-learned others. One thing in common for both setups is that you need to set a lot of paths in your task configurations, and if you decide to change a path, you have to do it all over, which can be a hassle. However, if you could store all your project variables in a JSON file you would only have to change the path in one single place.

For this to work you don’t even need any Gulp plugins, all you need to add are the two following lines of code in your gulpfile.js

var fs = require('fs');
var config = JSON.parse(fs.readFileSync('./config.json'));

That will use the Node.js File System to load and parse the JSON to an object that we ca use.

So let’s take this example of our config.json

{
  "myvar": "value",
  "paths": {
    "myvar2": "value2",
    "myvar3": "value3"
  }
}

If we load that into our config variable we can access it just like this

var fs = require('fs');
var config = JSON.parse(fs.readFileSync('./config.json'));
console.log(config.myvar);
console.log(config.paths.myvar2);
console.log(config.paths.myvar3);

As I’m a big fan of clean code I take advantage of this technique and store all paths and variable plugin options in a lone JSON file. This makes it easier for me and my co-workers to change stuff between projects without the need to change the Gulp tasks.

Thoughts and comments

Share your thoughts on this

Your email address will not be published.