DRY up gulp tasks

Seth

Say I have these two gulp tasks:

gulp.task('js.task1', function() {
  return gulp.src(config.js1.src)
  .pipe($.plumber())
  .pipe($.if(production, $.uglify()))
  .pipe(gulp.dest(config.js1.dest));
});

gulp.task('js.task2', function() {
  return gulp.src(config.js2.src)
  .pipe($.plumber())
  .pipe($.if(production, $.uglify()))
  .pipe(gulp.dest(config.js2.dest));
});

They're both identical aside from the src and dest locations.

Is it possible to do something like this?

function jsMoveGeneric(src, dest) {
  return gulp.src(src)
  .pipe($.plumber())
  .pipe($.if(production, $.uglify()))
  .pipe(gulp.dest(dest));
}

gulp.task('js.task1', jsMoveGeneric.bind(null, config.js1.src, config.js1.dest));
gulp.task('js.task2', jsMoveGeneric.bind(null, config.js2.src, config.js2.dest));
ssube

You don't even need to complicate it that much. Your two function bodies are almost identical, save a few parameters.

function uglyPlumber(src, dest) {
  return gulp.src(src)
    .pipe($.plumber())
    .pipe($.if(production, $.uglify()))
    .pipe(gulp.dest(dest));
}

gulp.task('js.task1', function() {
  return uglyPlumber(config.js1.src, config.js1.dest);
});

gulp.task('js.task2', function() {
  return uglyPlumber(config.js2.src, config.js2.dest);
});

Remember that passing strings (or objects) and returning promises works just fine in JS, so you can move the body into a more general function and return the results from there. So long as you return the output of that function from the task, gulp does not know or care what was actually called.

If you know you'll always pass an object with src and dest properties, you can take advantage of that to do:

function uglyPlumber(path) {
  return gulp.src(path.src)
    .pipe($.plumber())
    .pipe($.if(production, $.uglify()))
    .pipe(gulp.dest(path.dest));
}

gulp.task('js.task1', function() {
  return uglyPlumber(config.js1);
});

There's also an emerging pattern with gulp to isolate tasks into their own modules (files) when they start to become complex, so you can write some of these as helper functions in a file of their own and require that. This can be useful when you have a complicated build, as it allows you to unit test parts of the build script.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related