A simple Gulp build task

I've been using Gulp as my task runner of choice for a few months now. Slowly, I've refined my gulpfile to a version that I'm happy with.

My gulpfiles have typically had a few tasks: compile Sass, hint and minify Javascript, and watch for changes and recompile while I work. I'd have a few tasks to queue up a build and watching for changes. While that is probably enough for most, I wanted a slightly more sophisticated task for building development and production files. Ideally, I want to have one task that I can add some flags to, like this:

$ gulp build --production

The difference being, if I add this --production flag, I want the compiled files to be minified.

Where it clicked for me

A couple of days ago, Headstart, an automated front-end setup tool was released. As I usually do with this type of project, I jumped over to Github and started scouring the source code. The gulpfile that Florian wrote was a thing of beauty.

I immediately latched on to a few Gulp or Node plugins to help my in my quest: gulp-if, run-sequence, and minimist.

Gulp-if allows you to conditionally run a task if a a condition is met. In my case, I want to test if I'm creating a production build, so my files get minified. Here's an example of where I'm testing if we're creating a production build and adding a .min suffix to the filename.

.pipe(gulpif(isProduction, rename({suffix: '.min'})))

Run-sequence allows you to run a series of dependent tasks in the order you choose. The best part of all, is that you can run tasks in parallel. In the example below, the clean task is run, then all the other task are run in parallel.

sequence(
        'clean',
        [
            'sass-main',
            'sass-ie',
            'scripts-main',
            'scripts-ie',
            'images',
            'other'
        ],
        function() {
            console.log(chalk.green('✔ All done!'))
        }
    )

Minimist is what allows us to write flags on the build task from the command line. As above, if I add the --production flag, a minified production build is created. I'm also recognizing a --watch flag, which queues up the watch task after the initial build.

If you want to see the full gulpfile with all tasks, I've created a Gist for your viewing.

In Closing

I hope this can be useful to you. If there's one thing to take away, it's to be curious and read other developers source code. You can learn much from other's work if you take the time to explore.

If you have any feedback or suggestions, feel free to hit me up on Twitter @centerdrive – I'd be interested in learning about your build processes and tasks using Gulp or any other tools.