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);
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With