DRY up gulp tasks

狂风中的少年 提交于 2019-12-11 04:02:51

问题


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));

回答1:


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.



来源:https://stackoverflow.com/questions/33395213/dry-up-gulp-tasks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!