Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create parameterized and reusable gulp tasks

Tags:

node.js

gulp

Is there a way to make this generic to the point where I can have one copy of it and pass the config item, and file list into it rather than duplicating it for every file/config combination?

I'd love to have something like

gulp.task('foo_test', function (cb) {
   run_tests(files.foo_list, config.fooCoverage);
   cb();
}

Note on potential oddities in the code I'm using lazypipe and gulp-load-plugins full file here

// test the server functions and collect coverage data
gulp.task('api_test', function (cb) {
    gulp.src(files.api_files)
      .pipe(istanbulPre())
      .on('end', function () {
          gulp.src(files.api_test_files)
            .pipe(mochaTask())
            .pipe(istanbulAPI())
            .on('end', cb);
      });
});

var istanbulAPI = lazypipe()
  .pipe(plugins.istanbul.writeReports, config.apiCoverage);

config =  {
   apiCoverage: {
        reporters: ['json'],
        reportOpts: {
            json: {
                dir: 'coverage',
                file: 'coverage-api.json'
            }
        }
    },
like image 926
skarface Avatar asked Mar 13 '23 01:03

skarface


1 Answers

Gulp is just JavaScript.

You can write plain old regular functions, just as you normally would:

function run_tests(srcFiles, srcTestFiles, coverageConfig, cb) {
  var istanbul = lazypipe()
    .pipe(plugins.istanbul.writeReports, coverageConfig);

  gulp.src(srcFiles)
    .pipe(istanbulPre())
    .on('end', function () {
       gulp.src(srcTestFiles)
         .pipe(mochaTask())
         .pipe(istanbul())
         .on('end', cb);
     });
}

gulp.task('unit_test', function (cb) {
   run_tests(files.lib_files, files.unit_test_files, config.unitCoverage, cb);
});

gulp.task('api_test', function (cb) {
   run_tests(files.api_files, files.api_test_files, config.apiCoverage, cb);
});

Note that the callback cb is just another parameter that is passed to the run_tests function. If it was called immediately after calling run_tests that would signal task completion to gulp before the asynchronous code in run_tests has actually finished.

like image 74
Sven Schoenung Avatar answered Mar 24 '23 13:03

Sven Schoenung