Gulp - 使用参数启动任务 [英] Gulp - start task with an argument
问题描述
所以我正在尝试创建一个 gulp 工作流程,并且我想为一些任务实现选项,例如 gulp copy-images --changed
.现在,我创建了一个监视任务,它显然监视所有图像文件,它应该使用 --changed 标志启动 copy-images
.
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?
提前致谢!
推荐答案
Gulp 不提供指定任务选项的内置方式.您必须使用外部选项解析器模块,例如 yargs
.请参阅 this question 了解有关该主题的更多信息.
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.
这也意味着将 ['copy-images --changed']
之类的内容传递给 gulp.watch()
将不起作用.整个字符串将被解释为任务名称.
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
将执行//一些其他代码
.gulp copy-images --changed
将执行//一些代码
.gulp watch
将执行//some code
任何时候监视的文件发生变化.
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 - 使用参数启动任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!