Working with Gulp.js

Start with every new project, we have some tasks which we repeat over and over again, for example compiling, minifying, concatenating, testing etc, Gulp is a tool to automate these process so we don’t have to go through all those repetitive tasks each time we make changes to our code.

 

Tasks we commonly perform repetitively -

  • CSS and JS Compilation ( Sass, Less, Coffee, etc )
  • Adding Vendor Prefixes  
  • Minify JavaScript and CSS
  • Concat ( Concatenating multiple JS or CSS FIles )
  •  Running Tests

Gulp can automate these process so you don’t have to remember which task to perform and what is the sequence of in which these tasks will be performed.

 

Setting up your Workflow

We have to setup our environment before we can use gulp, I assume that you have nodejs installed, if not you have to install Node before installing gulp.

Once Node is installed, Follow these steps to install gulp.

  • Install Gulp globally 
  • Initialize npm( or manually create package.json file )
  • Install gulp locally
  • Create gulpfile.js

 

Let's Install gulp globally so we can access it from command line anywhere.

npm install -g gulp

We can test if gulp is installed properly, running following command will verify the version of gulp.

gulp -v

Next step is to go to Root folder of your project and initialize npm, it will create package.json file where we will save our dependencies.

npm init

You will be asked for name, version, description, etc of project which you can fill or leave them blank to accept defaults.

Now we need to install gulp locally, this will make sure that the version of gulp we are using is locked down and we will run our gulp tasks using this local version of gulp.

Go to Root folder of your project and run following command,

npm install --save-dev gulp

--save-dev is really important, this will save our dependencies in package.json file which we created using npm init.

Last thing we need to do is create gulpfile.js file in our project root folder, We will use this file to write our tasks.

 

Basics Of Gulp

Gulp has 4 main top level API's,  let’s look at those-

  • gulp.task()
  • gulp.src()
  • gulp.dest()
  • gulp.watch()

 

gulpfile.js can have many tasks and we use gulp.task() to define each task.

//gulpfile.js

var gulp = require('gulp');

gulp.task(‘javascripts’, function() {
	// your code
}) 

gulp.task(‘sass’, function() {

})

gulp.task(‘some-task’, function() {

})

gulp.task(‘css’, [‘sass’, ‘some-task’],  function() {
	//your code
})

We can have two or three parameters in task function.

First parameter:  Name of the task which we are free to name whatever we want

Second parameter:  Anonymous function where we write our code.

In case of three parameters Second parameter will have array of dependent task, these dependent tasks will run before running our current task.

 

gulp.src() is a function where we point our source file which we want to process, it returns stream which can be processed further using pipe() function.

gulp.task(‘javascripts’, function() {

	gulp.src(‘/js/src/**/*.js’)
                   .pipe(gulp.dest(‘js/dest’));
})

First parameter: File System Glob, it emits files which matches the pattern.

Second parameters(optional): Object where we can define base path, buffer, read.

 

gulp.dest() points to the destination folder where our file will go after being processed.

First parameter: Destination folder path

Second parameter(optional): Object where we can define file permission in unix format ( 700, 644, etc).

 

gulp.watch() allows us to watch files and performs the task when file changes.

gulp.watch(‘/js/src/**/*.js’, [‘javascripts’]);

gulp.watch(‘/js/src/**/*.js’, function() {
	
})

watch function have two signatures, In second parameter we can pass array of tasks to run or function.

 

Common Tasks

Gulp is very minimal in size and default functionality but can be extended using plugins, We can install the plugins we require, to perform each of these tasks we need to get additional plugins.

Complete list of plugins can be found here.

 

Directory Structure

stylesheets/
|    css/
|    sass/
|    |    _footer.scss
|    |   _global.scss
|    |    app.scss
js/
|    src/
|    |	script1.js
|    |	script2.js
|	dest/
index.html
gulpfile.js
package.json

 

JSHint

Checking syntax error in one JavaScript file is easy these days with modern code editors, but if project is large enough and you have hundreds of files it might become cumbersome, let’s use gulp to hint( error checking ) our files.

Before we can use Jshint, We need to install gulp-jshint plugin, let’s run the following command in our project root folder to install plugin, additionally we can install jshint-stylish plugin for stylish output purposes.

npm install gulp-jshint jshint-stylish --save-dev

To use this plugin we need to require module in our gulpfile.js, lets write code to hint our files.

//gulpfile.js

// getting required module to perform jshint task   
var gulp = require('gulp'),
      jshint = require('gulp-jshint'),
      stylish = require('jshint-stylish');

//creating task scripts 
gulp.task('scripts', function () {

return gulp.src('js/src/*.js')				//getting all js files from js/src/ folder    
            .pipe(jshint())					//performing jshint task
	.pipe(jshint.reporter(stylish))			//telling jshint reporter to use jshint-stylish, 
	.pipe(gulp.dest('js/dest'));			//finally putting files inside js/dest folder

});

 

Now to run our task, type the following command in terminal or command prompt.

gulp scripts

This will run the task and if any errors are found they will be highlighted in colors thanks to jshint-stylish.

 

Concatenation and Minification of Scripts

Right now our scripts is just hinting files and spitting them out in js/dest folder, let’s modify our scripts task to perform concatenation and minification before putting them in js/dest folder.

We need two additional plugins gulp-concat and gulp-uglify to perform these tasks, let’s get them first.

npm install gulp-concat gulp-uglify --save-dev

Now lets write our task-

//gulpfile.js
var gulp = require('gulp');
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish');


gulp.task('scripts', function () {
    
return gulp.src('js/src/*.js')
            .pipe(jshint())
            .pipe(jshint.reporter(stylish))
            .pipe(concat('main.js'))		//concatenating all files into main.js
            .pipe(uglify())					// minifying main.js
            .pipe(gulp.dest('js/dest'));	// putting main.js to js/dest folder

});

Run gulp scripts command again to perform the task.

 

Sass Compilation and Minification

Let’s use gulp to compile and minify sass files, we need two more plugins to perform these tasks, gulp-sass will compile sass files and gulp-minify-css will minify our compiled css file, let’s get those.

npm install gulp-sass gulp-minify-css --save-dev

We are going to create new task sass where we will write our code.

//gulpfile.js
//getting our dependencies
var gulp    =   require('gulp');
      sass = require('gulp-sass'),
      cssmin = require('gulp-minify-css');


gulp.task('sass', function () {
    return gulp.src('stylesheets/sass/app.scss')		// getting source file
                .pipe(sass())					// compile to css
                .pipe(cssmin())					// minify file for production
                .pipe(gulp.dest('stylesheets/css'));	        // putting file to stylesheets/css folder
});

Let’s run gulp sass command to perform our task, this will create app.css file in stylesheets/css folder.

As you can see it’s quite easy, with just few lines of code we can do quite a bit, but right now we have only ran one task, what about when we have to run multiple tasks, let’s see how we can run multiple tasks with one command and also watch for changes so we don’t have run command each time we make changes in our code.

gulp provides us default task which we can use to perform multiple task or even watch for changes and run task again if something changes.

Let’s put everything together and create default task to perform all tasks for first time and then watch for changes.

//gulpfile.js
var gulp    =   require('gulp');
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    sass = require('gulp-sass'),
    cssmin = require('gulp-minify-css');


gulp.task('scripts', function () {
    return gulp.src('js/src/*.js')
            .pipe(jshint())
            .pipe(jshint.reporter(stylish))
            .pipe(concat('main.js'))
            .pipe(uglify())
            .pipe(gulp.dest('js/dest'));
});

gulp.task('sass', function () {
    return gulp.src('stylesheets/sass/app.scss')
                .pipe(sass())
                .pipe(cssmin())
                .pipe(gulp.dest('stylesheets/css'));
});


//creating watcher task
gulp.task('watch', function () {
    gulp.watch('js/src/*.js', ['scripts']);		        //running scripts task on change
    gulp.watch('stylesheets/sass/app.scss', ['sass']);		// running sass task on change
});

//initially running scripts and sass tasks and also running watch task to watch for changes
gulp.task('default', ['scripts', 'sass', 'watch']);

 

Concusion

As you can see gulp is really helpful tool to have, now we can really focus on our code instead to wasting hours of time doing these tasks manually.

Gulp can do much more than what we have done here, it can run tests for js files, php files and lots more, gulp has thousands of plugin to perform different tasks.

Get the source code

Something to say? Tell us in comment section.