我正在尝试基于 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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!