Search code examples
gulpgulp-4

How to repeatedly launch a task from another task in gulp 4


I recently upgraded to gulp 4 and I am trying to solve a long standing issue of with my export process.

In short I have 3 (or more) independent folders in my project. By independent I mean that they each have their own bundle.js and global.css file. I have setup a target variable in my gulpfile which is used to create all the paths gulp needs for that target.

In the current situation when I want to export my entire project I need to manually change the target variable in the gulpfile and then run the export task.

I need something that works like the following (as the other_folders array can change)

/*----------  Exports current target  ----------*/
gulp.task('export', gulp.series(to_prod,'export_files', 'export_scripts_and_styles', 'export_fonts', 'export_core'));

/*----------  Exports all targets  ----------*/
gulp.task('export_all', function(done){
    var needs_exporting = other_folders.concat("website");

    needs_exporting.forEach(function(export_this){
        target = export_this;
        set_paths();

        // Here it needs to fire the generic export task
        gulp.series('export');
    });

    done();
});

The problem is that I cannot seem to find a way to call a gulp task in the forEach loop. Is there a way to do this or do I need a workaround?


Solution

  • Calling gulp.series('export') doesn't immediately start the export task. It just returns a function that you have to call in order to start the export task.

    However calling the returned function doesn't start the export task immediately either. The function is asynchronous. Only later is the export task actually started.

    The easiest way to run an asynchronous function for each element of a collection in series is to use the eachSeries() function that's provided by the async package:

    var async = require('async');
    
    gulp.task('export_all', function(done){
        var needs_exporting = other_folders.concat("website");
    
        async.eachSeries(needs_exporting, function(export_this, cb) {
            target = export_this;
            set_paths();
    
            gulp.series('export')(cb);
        }, done);
    });