Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating tasks using a loop [gulp]

Tags:

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); 
like image 728
cmancre Avatar asked Apr 09 '14 16:04

cmancre


People also ask

How do I create a task in Gulp?

gulp. task('task-name', function() { // Stuff here }); task-name refers to the name of the task, which would be used whenever you want to run a task in Gulp. You can also run the same task in the command line by writing gulp task-name .


2 Answers

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.

like image 164
OverZealous Avatar answered Oct 10 '22 21:10

OverZealous


Capture the value of 'key' variable on each iteration using IIFE. In your example, at the moment of concat invocation loop will be finished already and variable key will have the last value.

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

For detailed explanation see this function closures - Avoiding the Reference Problem section

like image 36
oaleynik Avatar answered Oct 10 '22 19:10

oaleynik