Starting with gulp

Standard

Gulp – The streaming build system. As the name say, gulp is a tool for building the system.

In short, a tool which can help with automating the build process. Gulp is a javascript based build tool that uses nodejs as its running environment.

Its a task runner which can help with some very important and frequently used task like JS and CSS minification, compiling SASS etc.

Lets dive into gulp.

#Installation

Gulp requires nodejs to get installed. If you don’t have nodeJS, please install it first from its website. http://nodejs.org

After installing node, you have to run below command for gulp installation.

$ sudo npm install gulp -g

where $ sign just symbolize the bash/terminal. sudo may only required on linux and mac machines.

Now we have gulp globally installed on our system. Lets move to next step.

#Getting ready

Let’s create a gulp project. We can use npm init command to initialize the project that can help us to create a package.json file to manage our project dependencies.

Create a folder gulp-pro and start command prompt/terminal and type.

$ sudo npm init

npm init will prompt for your input and create a package.json file where we can declare our project dependencies. Gulp is an example of project dependency.

Now lets install gulp as dev dependency into our project.

$ sudo npm install gulp --save-dev

This will install gulp inside our project folder and will also make an entry in package.json file.

Our package.json file will look like this:

{
 "name": "gulp-pro",
 "version": "1.0.0",
 "description": "gulp practise",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "sgoyal.net",
 "license": "ISC",
 "devDependencies": {
 "gulp": "^3.9.1"
 }
}

gulp is listed under devDependencies.

#Project Folder Structure

Next step is to decide directory structure of our project. Lets keep it simple and straight forward for the moment. Our project directory structure will look like this.

app folder will have our project source code, dist folder is for release code, gulpfile.js is configuration file for gulp.

#Hello Gulp

Its time for saying Hello Gulp i.e our first gulp task.

Gulp is very simple and easy to understand library having just 4 top level methods.

  • gulp.task
  • gulp.src
  • gulp.dest
  • gulp.watch

Lets look at them one by one.

gulp.task define your task that you want to perform. it has three parameters name, dependencies, function.

Where name is simply your task name, dependencies are the tasks that you want to get completed before execution and function is the function which will execute and do the magic for you. dependencies parameter is optional.

gulp.src is to point your source files on which you want to perform. Let’s say, we want to minify our javascript files that are in js folder then path to js folder will comes under gulp.src method.

gulp.dest represent the destination directory where you want to put your files after performing a particular task.

gulp.watch is used to add sort of listeners on source file and react as soon as they get change. The most useful use case could be reloading the browser as soon as our source files get updated.

Let’s write a gulp task.

First step is to add require gulp module in our gulpfile.js

var gulp = require ('gulp');

The require statement tells nodejs to look for the gulp module and assign its content to gulp variable.

gulp.task ("hello", function(){

    console.log ("hello gulp");

});

Now its time to run.

$ gulp hello

Output will be

Congratulations 🙂

The base format of a gulp task look like this.

gulp.task ("task-name", function () {

  gulp.src ("path-to-files").

  pipe (gulp-plugin()).

  pipe (gulp.dest("path-to-destination"));

});

Where pipe method is used to pass output stream to passed module.

#Multiple files into gulp.src

Sometimes we require to perform a task on more then one file. For example, compressing all .css files and moving them to some other folder. So, we need to apply some logic/regular expression to match a pattern to select multiple files. Here Globs comes into the picture.

When we use globs, program checks file name for defined pattern and return the result.

Some useful globs are:

  • *.js: The * pattern matched all the files with extension .js In this case we are matching all js files present in root folders.
  • **/*.js: This is advanced version of *which match for all files with js extension present at root folder as well as any child directory.
  • *.+(js|css): + and () operator instruct gulp to match multiple pattern separated by |. In this case, we are matching all files with extension js and css
  • !exclude.css: The ! direct gulp to exclude pattern from its match. In this case, gulp will match all files excluding exclude.css file.

#Example – Optimizing CSS and JS

A very useful use case can be minimizing your css and javascript files and copy them into the dist folder. Let’s take a look how?

We are going to need some modules to achieve above goal.

  • gulp-uglify We will use gulp-uglify package for minimizing javascript.
  • gulp-if check conditions
  • gulp-cssnano compress css files.

There are lots of packages available at gulp project site. Please explore. http://gulpjs.com/plugins/

Let’s install above plugins and save them in our dev dependencies by running below commands.

$ sudo npm install gulp-uglify --save-dev
$ sudo npm install gulp-if --save-dev
$ sudo npm install gulp-cssnano --save-dev

Our gulpfile.js will look like this.

var gulp = require ('gulp');
var gulpIf = require ('gulp-if');
var uglify = require ('gulp-uglify');
var cssNano = require ('gulp-cssnano');

gulp.task ("compress", function () {
	return gulp.src ('app/**/*.*')
	.pipe(gulpIf('*.js', uglify()))
	.pipe(gulpIf('*.css', cssNano()))
	.pipe(gulp.dest('dist'));
});

Above example simply pick files from app directory and if matched files are .js then uglify plugin will be executed and if files are .css then cssNano will get into picture and finaly all the processed files will be written to dist folder.

Run gulp using command gulp compress

Our compressed files should be in dist folder.

#Verdict

Gulp is a very useful tool to automate your task. Task list can be endless such minification, browser auto sync, compiling sass files, etc. Please explore available plugins at http://gulpjs.com/plugins/ at choose your comfert.

 

Happy Learning!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s