使用循环创建任务 [gulp]

creating tasks using a loop [gulp](使用循环创建任务 [gulp])
本文介绍了使用循环创建任务 [gulp]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试基于 jsFiles 对象动态创建任务(缩小和连接).键将给出目标文件名,数组包含 src 文件.当我运行 gulp 时,我看到所有任务名称都在运行,但它只写入最后一个键,在这种情况下是 group2.js.这里有什么问题?

I'm trying to dynamically create tasks (minify and concat) based on jsFiles object. The key will give the destination file name and the array contains the src files. When I run gulp I see all the tasks names being ran but it only writes the last key which is group2.js in this case. What's wrong here?

// imports here

var jsFiles = 
{
    group1:[file1.js,file2.js],
    group2:[file2.js,file3.js]
};

for (var key in jsFiles)
{
    gulp.task(key, function() {
        return gulp.src(jsFiles[key])
        .pipe(jshint())
        .pipe(uglify())
        .pipe(concat(key + '.js'))  // <- HERE
        .pipe(gulp.dest('public/js'));
    });
}

var defaultTasks = [];
for (var key in jsFiles)
{
    defaultTasks.push(key);
}
gulp.task('default', defaultTasks);

推荐答案

另一种选择是使用函数式数组循环函数结合Object.keys,像这样:

Another option is to use functional array looping functions combined with Object.keys, like so:

var defaultTasks = Object.keys(jsFiles);

defaultTasks.forEach(function(taskName) {
   gulp.task(taskName, function() {
       return gulp.src(jsFiles[taskName])
          .pipe(jshint())
          .pipe(uglify())
          .pipe(concat(key + '.js'))
          .pipe(gulp.dest('public/js'));
   });
});

我觉得这样更简洁一些,因为循环和函数在同一个地方,所以更容易维护.

I feel like this is a little cleaner, because you have the loop and the function in the same place, so it's easier to maintain.

这篇关于使用循环创建任务 [gulp]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)