Creating a maintainable gulpfile.js

Configuring Gulp across multiple projects can become tedious and tiresome. Fortunately, it's relatively easy to create a reusable and maintainable gulpfile.js

September 10, 2017

It may be the new kid on the block, but why would you use Webpack for literally everything? Don’t get me wrong, it has its use cases where it is perfect, such as working with the latest frameworks, such as Angular or React. But for a vanilla JavaScript project it just seems like overkill.

In these cases my go to build tool of choice is Gulp on mostly all projects which usually don’t require much more than linting, transpiling, running unit tests, and deploying.

The are only two downsides to Gulp - or at least its configuration - as I see it. Both of them pertaining to maintainability. But hopefully, we’ll be able to address those today.

What are Gulp’s configuration downsides?

The number of plugins we actually need to get Gulp working ‘just the way we want it’ can be incredibly large. This means that the first lines of code in any gulpfile.js usually consist of importing or requireing (depending on your flavour) any number of plugins.

This list of plugins is usually a mirror of much of the contents of the devDependencies in our package.json file. Remove a plugin from one, we need to remember to remove it from the other.

Often our gulpfile.js is written in tandem with the rest of our project. This means lots of hardcoded globs, paths, and filenames littering it. Again any changes to one, requires a change to the other.

Our package.json should be concerned with the meta data of our project, such as its structure and what dependencies it may have.

Our gulpfile.js should be concerned with building our project.

Duplicating all of that information again goes against the DRY (Don’t Repeat Yourself) principle and the principle of separation of concerns.

Once we’ve defined a pattern to solve these issues, configuring your Gulp build tasks will be so easy, you’ll wonder what you’ve been doing for all these years …at least I did.

Importing our Gulp plugins

Usually our standard gulpfile starts off with 20+ lines of import lib from 'gulp-lib'; or const lib = require('gulp-lib'); over and over…and over.

Question: Why do we need to do this?

Answer: We don’t.

We’ve already declared all of our dependencies in our package.json under devDependencies, so why not just import them from there?

Luckily for us there’s a handy Gulp plugin that can do just that: gulp-load-plugins. So the first thing we’ll do is install that.