One of the most powerful aspects of gulp, is the ability to put multiple tasks together. Doing this allows you, the developer to run a single command, and then have gulp execute multiple tasks for you. In this video you’ll see how to do that!

There’s one huge problem and it could actually turn into a pretty big one.
Gulp normally runs all tasks concurrently, since that is the fastest way to complete the tasks, and without telling gulp which task is dependent on which task, gulp will run all of these tasks at the same time in parallel.

That means the concatScripts task will consistently finishe after the minifyScripts task. Which means, each time we run gulp build, the uglify task is using the app.js file that was already there, and this is no bueno.

 

To solve this, check out the following code changes.

"use strict";

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  maps = require('gulp-sourcemaps');

gulp.task("concatScripts", function() {
    return gulp.src([
        'js/jquery.js',
        'js/sticky/jquery.sticky.js',
        'js/main.js'
        ])
    .pipe(maps.init())
    .pipe(concat('app.js'))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('js'));
});

gulp.task("minifyScripts", ["concatScripts"], function() {
  return gulp.src("js/app.js")
    .pipe(uglify())
    .pipe(rename('app.min.js'))
    .pipe(gulp.dest('js'));
});

gulp.task('compileSass', function() {
  return gulp.src("scss/application.scss")
      .pipe(maps.init())
      .pipe(sass())
      .pipe(maps.write('./'))
      .pipe(gulp.dest('css'));
})

gulp.task("build", ['minifyScripts', 'compileSass']);

gulp.task("default", ["build"]);

 

  • return gulp.src([...
    Adding this return statement acts as a promise. Without the return statement, other tasks won’t know when the concatScripts tasks has finished and so they’ll start right away, instead of waiting for their dependencies to finish.
  • gulp.task("minifyScripts", ["concatScripts"], function() {...});
    Making concatScripts as a dependency of minifyScripts.
  • gulp.task("default", ["build"]);
    Use the default gulp task to to build their website for production.
    This is a place where following convention can be really helpful for others.