Gulp Tasks in Detail

In this post I am going to explain about the 5 methods availabe in Gulp and it's functionality in detail.In the earlier post, I have gone through the process of setting up Gulp in your local Windows box and also about getting started with a simple task. You can refer that post here.

As I mentioned in that post, there are only five methods available in git, namely

  1. task
  2. run
  3. watch
  4. src
  5. dest

gulp.task() is used for defining our tasks. Expected parameters are task name, array of task names and a function that performs the task. 

Syntax 

 gulp.task('<task name>',['<task 1>','<task 2>'], funtion{});

  The second parameter is optional, so the task method can have two forms

 gulp.task('parenttask', funtion{
// perform parent task
});

 

  gulp.task('childtask', ['parenttask'], funtion{
// perform child task after parent task is completed
});

gulp.src() is used to provide the path for our source files and it takes two parameters, one glob and an optional options object. In the src method, .pipe function is called extensively to chain output into other methods. 

Syntax

gulp.task('<glob>', funtion{});

gulp.dest() is used to specify the destination for files to be written into. We can use src and dest methods to do a file copy task like the one below.

Syntax

gulp.task("<desination folder/file.>");

Usage

  gulp.task('fileCopy' funtion{
gulp.src('scripts/*.js')
.pipe(gulp.dest('content/scripts'));
});

gulp.watch() method is also having two signatures, the first one will take a glob, options object which is optional and an array of tasks as parameters and the second one takes a glob, options object and a callback method.     The last two parameters are optional for the second one. These two methods returns an EventEmitter instance that emits the change events. 

Syntax

gulp.watch('<glob>' ,['<task name>']);
gulp.watch('<glob>' ,['<task name>'], function(){});

Usage

  gulp.watch('scripts/**/*.js' ,['jshintTask']);

          This code block will fire the jshintTask whenever there is a change in files who has js extention in the folder specified for the first parameter.

  gulp.watch('scripts/**/*.js' , function(event){
console.log("callback called");
});

Here instead of specifying the task, we are defining the callback method and it will get executed once the task is triggered.

gulp.run() is used to run a task by it's name

Syntax

  gulp.run('<task name>');

Usage

  gulp.run('fileCopy');

        

        


No Comments

Add a Comment