Gulp - start task with an argument

☆樱花仙子☆ 提交于 2019-12-03 21:58:52

问题


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.


来源:https://stackoverflow.com/questions/36648656/gulp-start-task-with-an-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!