Gulp - start task with an argument

前端 未结 1 818
滥情空心
滥情空心 2021-01-07 05:05

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 tha

相关标签:
1条回答
  • 2021-01-07 05:16

    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.
    0 讨论(0)
提交回复
热议问题