我正在尝试基于 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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Browserify,Babel 6,Gulp - 传播运算符上的意外令牌Browserify, Babel 6, Gulp - Unexpected token on spread operator(Browserify,Babel 6,Gulp - 传播运算符上的意外令牌)
是否可以将标志传递给 Gulp 以使其以不同的方式Is it possible to pass a flag to Gulp to have it run tasks in different ways?(是否可以将标志传递给 Gulp 以使其以不同的方式运行任务
为什么我们需要在全局和本地安装 gulp?Why do we need to install gulp globally and locally?(为什么我们需要在全局和本地安装 gulp?)
如何一个接一个地依次运行 Gulp 任务How to run Gulp tasks sequentially one after the other(如何一个接一个地依次运行 Gulp 任务)
由于 MIME 类型而未加载样式表Stylesheet not loaded because of MIME-type(由于 MIME 类型而未加载样式表)
打开 Javascript 文件时 Visual Studio 2015 崩溃Visual Studio 2015 crashes when opening Javascript files(打开 Javascript 文件时 Visual Studio 2015 崩溃)