问题描述
所以我正在尝试创建一个gulp工作流程,并且希望为某些任务实现选项,如 gulp copy-images --changed
。现在,我创建了一个明显监视所有图像文件的监视任务,它应该使用--changed标志启动 copy-images
。
理想情况下,我想这样做:
gulp .task('copy-images',function(){
//一些代码
});
gulp.task('watch',function(){
gulp.watch(config.images,['copy-images --changed']);
}) ;
我也很清楚我可以这样做:
gulp.task('copy-images',function(){
//一些代码
});
gulp.task('copy-images-changed',function(){
//一些代码
});
$ b gulp.task('watch',function(){
gulp.watch(config.images,['copy-images']);
});
但这意味着重复的代码。
任何拥有解决方案或者一些建议的人?
在此先感谢!
Gulp不提供内置的指定任务选项的方式。您必须使用外部选项解析器模块,如。参见以获取更多关于该主题的信息。
这也意味着传递类似于 ['copy-images - 改变']
为 gulp.watch()
不起作用。整个字符串将被解释为一个任务名称。
最好的方法是将任务的代码分解为一个函数,然后调用这个函数从你的任务和你的手表:
var argv = require('yargs')。argv;
函数copyImages(opts){
if(opts.changed){
//一些代码
} else {
//一些其他代码
$ b gulp.task('copy-images',function(){
copyImages(argv);
});
gulp.task('watch',function(){
gulp.watch(config.images,function(){
copyImages({changed:true});
});
});
以上内容应涵盖您的所有基础:
gulp copy-images
会执行 //其他一些代码
li>
gulp copy-images --changed
会执行 //一些代码
。
gulp watch
会执行 //一些代码
已改变。
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!
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.
这篇关于咕嘟咕嘟咕嘟咕嘟咕嘟咕嘟咕嘟咕嘟咕嘟咕嘟咕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!