• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How To: Basic Tasks in Gulp.js

Front End Development · July 21, 2014

If you’re familiar with GruntJS, you might be familiar with Gulp.js. Both are very similar, Gulp is the newer kid on the block that requires significantly less configuration to write tasks.

If you’re new to Gulp or perhaps already use it, but not sure how to do specific tasks with it, see below for a list of basic tasks you can achieve in Gulp.js.

There is a complete gulpfile.js at the bottom of this page containing all include files as well as directives if you struggle to follow along.

Error Handling using Plumber

Plumber is a plugin for Gulp that allows you to capture errors and not break the Gulp process when something goes wrong. All examples below will assume “gulp-plumber” is defined in your package.json file and installed.

At the top of your gulpfile.js, you will want to define the error handler all tasks will be using for Plumber.

var onError = function(err) {
    console.log(err);
}

Copying Files

Sometimes you might want to move files from one location to another. This example allows you to glob files from a source directory and all sub-directories within it.

Change the file extensions below to your desired extensions, or to copy everything in a folder and subfolders, replace the curly braces with a * so you have . which will grab everything and copy to the destination folder.

gulp.task('copyfiles', function() {
    gulp.src('./source_directory/**/*.{ttf,woff,eof,svg}')
    .pipe(gulp.dest('./destination_directory'));
});

Compress Images

Reduce the file size of your projects images by compressing them using this helpful task.

gulp.task('images', function() {
    var imgSrc = './src/images/**/*',
        imgDst = './images';

    return gulp.src(imgSrc)
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(changed(imgDst))
        .pipe(imagemin())
        .pipe(gulp.dest(imgDst))
        .pipe(notify({ message: 'Images task complete' }));
});

Compiling Sass/Compass

If you’re using Sass as your pre-processor of choice, then you’ll want to know how to compile your styles using Gulp.

Required plugins

  • gulp-compass
  • gulp-notify
gulp.task('styles', function() {
    return gulp.src('./src/sass/*.scss')
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(compass({
            config_file: './config.rb',
            css: './css',
            sass: './sass'
        }))
        .pipe(gulp.dest('./css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

Hinting Your Javascript

Ensure your Javascript conforms to appropriate coding guidelines, no missing semicolons, no repeated variables or scope issues. This is a must have in your workflow. To control how strict the hinter is, change the default value to any valid value.

Required plugins

  • gulp-jshint
  • gulp-notify
gulp.task('jshint', function() {
    return gulp.src('./src/scripts/*.js')
    .pipe(plumber({
        errorHandler: onError
    }))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(notify({ message: 'JS Hinting task complete' }));
});

Combine/Minify Your Javascript

Required plugins

  • gulp-concat
  • gulp-strip-debug
  • gulp-uglify
  • gulp-notify
gulp.task('scripts', function() {
    return gulp.src('./src/scripts/*.js')
        .pipe(plumber({
            errorHandler: onError
        }))
        .pipe(concat('app.min.js'))
        .pipe(stripDebug())
        .pipe(uglify())
        .pipe(gulp.dest('./js/'))
        .pipe(notify({ message: 'Scripts task complete' }));
});

Watching / Reloading For Live Changes

Having to keep calling “gulp” isn’t any fun, using gulp-livereload, we can spin up a liveReload server instance to watch our files and run certain tasks again (thus automating our front-end workflow). Take note of other tasks being called inside of this watch block, this is where our liveReload server action happens.

Required plugins

  • gulp-live-reload
  • gulp-notify
gulp.task('watch', function() {
    // Check for modifications in particular directories

    // Whenever a stylesheet is changed, recompile
    gulp.watch('./src/sass/**/*.scss', ['styles']);

    // If user-developed Javascript is modified, re-run our hinter and scripts tasks
    gulp.watch('./src/scripts/**/*.js', ['jshint', 'scripts']);

    // If an image is modified, run our images task to compress images
    gulp.watch('./src/images/**/*', ['images']);

    // Create a LiveReload server
    var server = liveReload();

    // Watch any file for a change in the 'src' folder and reload as required
    gulp.watch(['./src/**']).on('change', function(file) {
        server.changed(file.path);
    })
});

Final gulpfile.js

See below for a fully functional gulpfile.js complete with all of the required modules for running tasks.

Dwayne

Leave a Reply Cancel reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Konstantin
Konstantin
8 years ago

Nice overview. You may want to take advantage of `gulp-load-plugins` and `BrowserSync` like in this example:

https://github.com/kriasoft/static-site-starter/blob/master/gulpfile.js

0
Dwayne
Dwayne
Author
8 years ago

Konstantin,

This was more of a high-level traditional approach I went for to make the article easier to follow along. I can vouch for “gulp-load-plugins” though, I use it in my personal Gulpfile myself because it is a pain in the butt having to define so many variables and requires for including every Gulp plugin you want to use.

I might write a follow up or edit shortly showing how to use gulp-load-plugins because I think it’s invaluable.

Thanks for dropping by!

0

Primary Sidebar

Popular

  • Thoughts on the Flipper Zero
  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • How To Install Eufy Security Cameras Without Drilling or Using Screws
  • How To Get The Hash of A File In Node.js
  • Wild Natural Deodorant Review
  • The Most Common iPhone Passcodes (and how to guess them)
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • Improving The Coopers Australian Pale Ale Extract Tin (and other tips)
  • How to Record With the Neural DSP Quad Cortex in Reaper (DI and USB Recording)

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz