Gulp - start task with an argument

2019-02-19 08:20发布

问题:

So I'm trying to create a gulp workflow and I'd like to implement options for some tasks, like gulp copy-images --changed. Now, I've created a watch task that obviously watches all image files and it should start the copy-images with the --changed flag.

Ideally, I want to do something like this:

gulp.task('copy-images', function(){
    // some code
});

gulp.task('watch', function(){
    gulp.watch(config.images, ['copy-images --changed']);
});

I'm also very aware that I could do:

gulp.task('copy-images', function(){
    // some code
});

gulp.task('copy-images-changed', function(){
    // some code
});

gulp.task('watch', function(){
    gulp.watch(config.images, ['copy-images']);
});

but this means duplicate code.
Anyone with a solution or maybe some advice?

Thanks in advance!

回答1:

Gulp does not provide a built-in way of specifying options for tasks. You have to use an external options parser module like yargs. See this question for more on that topic.

This also means that passing something like ['copy-images --changed'] to gulp.watch() will not work. The entire string will just be interpreted as a task name.

The best approach for you would be to factor out the code of your task into a function and then call this function from both your task and your watch:

var argv = require('yargs').argv;

function copyImages(opts) {
  if (opts.changed) {
    // some code
  } else {
    // some other code
  }
}

gulp.task('copy-images', function() {
  copyImages(argv);
});

gulp.task('watch', function(){
    gulp.watch(config.images, function() {
      copyImages({changed:true});
    });
});

The above should cover all of your bases:

  • gulp copy-images will execute //some other code.
  • gulp copy-images --changed will execute //some code.
  • gulp watch will execute //some code any time a watched file is changed.


标签: gulp