gulpgulp-4

How do I group tasks?


I'm experimenting with gulp 4 and I have a couple of tasks(buildIndex, buildContent, buildStyling and buildScripts) that insert files in the build folder.

I'd like to group those tasks into one task, so I can execute the group at the top-level.

This is how I got it to work for now. It might not work in the future as this comment states that gulp 4 intents to execute all tasks at top-level.

const { src, dest, parallel, series, watch } = require('gulp');
const browserSync = require('browser-sync').create();
const clean = require('gulp-clean');
const uglify = require('gulp-uglify');
const sass = require('gulp-sass');
var rename = require('gulp-rename');

exports.default = series(
  rebuild,
  parallel(
    host,
    watchSource));

function rebuild(cb) {
  series(
    deleteBuild,
    build)();
  cb();
}

function host(cb) {
  browserSync.init({
    server: {
      baseDir: 'build'
    }
  });
  watch('build/**').on('change', browserSync.reload);
  cb();
}

function watchSource() {
  watch('src/**', rebuild);
}

function deleteBuild() {
  return src('build', { allowEmpty: true, read: false })
    .pipe(clean());
}

function build(cb) {
  parallel(
    buildIndex,
    buildContent,
    buildStyling,
    buildScripts)();
  cb();
}

function buildIndex() {
  return src('src/index.html')
    .pipe(dest('build'))
    .pipe(browserSync.stream());
}

function buildContent() {
  return src('src/content/**/*.html')
    .pipe(dest('build/content'))
    .pipe(browserSync.stream());
}

function buildStyling() {
  return src('src/styling/**/*.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(dest('build/styling'))
    .pipe(browserSync.stream());
}

function buildScripts() {
  return src('src/scripts/**/*.js')
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(dest('build/scripts', { sourcemaps: true }))
    .pipe(browserSync.stream());
}

What is the correct way to group tasks?


Solution

  • Edit:

    Your already declaring the default task in export.default. If you want to add another task that runs the tasks you mentioned, you can do it like this:

    Run the tasks in parallel:

    exports.mynewtask = parallel(buildIndex, buildContent, buildStyling, buildScripts);
    

    Run the tasks one after another:

    exports.mynewtask = series(buildIndex, buildContent, buildStyling, buildScripts);
    

    This seems to be the correct way for grouping tasks as you can see in this Gulp.js documentation for parallel().

    .

    The same with old Gulp syntax would be like this:

    const gulp = require("gulp");
    ...
    gulp.task('default', gulp.parallel('buildIndex', 'buildContent', 'buildStyling', 'buildScripts'));
    // or
    gulp.task('default', gulp.series('buildIndex', 'buildContent', 'buildStyling', 'buildScripts'));