Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Webdeveloper @ Will & Skill

Share


How to separate gulp tasks into multiple files

Mohammed HammoudMohammed Hammoud

Let us assume that you are working on a normal-sized project. You use gulp to compile your css/less/sass and javascript. You have created X number of tasks which you have included in gulpfile.js. You begin to feel that your gulpfile.js is cluttered. An anxiety grows within you, which is also the main factor that you get insomnia. You panic and start Googling like crazy in the hope of solving your anxiety when you suddenly stumble onto this post. You discover that Will & Skill has solved your problem by cleverly separating your gulp tasks into multiple files.

Separate gulp tasks into multiple files

Let us assume that we have five tasks in our gulpfile.js. The first step towards a better sleep is to create our folder/file structure for these tasks:

└── gulp
    └── tasks
        ├── watch.js
        ├── compass.js
        ├── copy-assets.js
        ├── build-js.js
        ├── deploy.js
└── gulpfile.js

...and just by looking at the structure, you have probably noticed that these five tasks are: watch, compass, copy-assets, the build-js and deploy. Which also takes us to the next step. It's time to move our tasks to their newly created files. Eg:

This deploy task inside of gulpfile.js:

gulp.task('deploy', [
        'copy-assets',
        'compass',
        'build-js',
    ])

...becomes this inside of gulp/tasks/deploy.js

var gulp = require('gulp');

module.exports = function () {
    gulp.task('deploy', [
        'copy-assets',
        'compass',
        'build-js'
    ])
};

Personally, I believe that communication is the key to a good relationship. And with that, we should tell gulpfile.js about what files we require to include when gulp will be used.

This is how our newly configurated gulpfile.js should look like:

require('./gulp/tasks/watch')();
require('./gulp/tasks/compass')();
require('./gulp/tasks/copy-assets')();
require('./gulp/tasks/build-js')();
require('./gulp/tasks/deploy')();

That's it! We'll keep our fingers crossed that your anxiety will disappear. Till next time!

Webdeveloper @ Will & Skill

Comments