I need to pass a parameter to a gulp task from ano

2019-05-23 16:46发布

问题:

I have gulp file that I use to create the Html and Js for multiple kinds of exams, Ex1, Ex2 etc

Here's the task I use to create these for Ex1. It has hardcoded a call to the makeEx1Html task, three other tasks and followed by a function call where I can pass a parameter:

gulp.task('make_prod_ex1', function () {
    runSequence(
        'makeEx1Html',
        'makeTemplate',
        'rename_bundle_css',
        'rename_bundle_js',
        function () {
            make_prod_index('ex1');
        });
});

Here's the task that's hardcoded for Ex1:

gulp.task('makeEx1Html', function () {
    return gulp.src(config.srcEx1Html, { base: process.cwd() })
          .pipe(print(function (file) {
              return "Found file " + file;
          }))
          .pipe(rename({ basename: 'base' }))
          .pipe(gulp.dest('./'));

});

Here's the function where I can pass a parameter:

function make_prod_index(name) {
    return function () {
        gulp.src('index.html')
       .pipe(htmlreplace({
           'css': 'content/bundles/css.min.css',
           'js': 'content/bundles/js.min.js'
       }))
       .pipe(eol())
       .pipe(lec({ eolc: 'CRLF' }))
       .pipe(replace('content/bundles/css.min.css', 'content/bundles/css-' + md5File('content/bundles/css.min.css') + '.min.css.gz'))
       .pipe(replace('content/bundles/js.min.js', 'content/bundles/js-' + md5File('content/bundles/js.min.js') + '.min.js.gz'))
       .pipe(rename('index-' + name + '.html'))
       .pipe(gulp.dest('./'));
    }
}

I would like to avoid having a specific task like 'makeEx1Html' and 'makeEx2Html' etc but I am not sure how to do this.

Note all these task needs to run in order which is why I'm using runSequence.

I would appreciate any suggestions. Ideally I would like the task that makes the Html to be a function that I can pass a parameter to but I am not sure how to fit this into my requirements.

回答1:

Ideally I would like the task that makes the Html to be a function that I can pass a parameter to

You can do just that, except you don't just pass your parameters to the function, but also a callback cb that will be called when your function is done:

function makeExHtml(files, cb) {
  return gulp.src(files, { base: process.cwd() })
    .pipe(print(function (file) {
        return "Found file " + file;
    }))
    .pipe(rename({ basename: 'base' }))
    .pipe(gulp.dest('./'))
    .on('end', cb);
}

In your gulp tasks you can then use the above makeExHtml() function and pass a callback that will execute the rest of your runSequence():

gulp.task('make_prod_ex1', function () {
  makeExHtml(config.srcEx1Html, function() {
    runSequence(
      'makeTemplate',
      'rename_bundle_css',
      'rename_bundle_js',
      function () {
        make_prod_index('ex1');
    });
  });
});