Language:

Search

Automate your Workflow with Gulp JS

  • Share this:
Automate your Workflow with Gulp JS

Introduction

In this Article, I’ll walk you through the basic yet useful steps to help you setup Gulp workflow in your project’s directory. Which will help you minify all of your Style & Script files etc into single file & boost up the total loading time of your web application with minimum number of HTTP requests to the server.

I am assuming that you might not familiar with the CLI (Command Line Interface) before, so I will take you through each step in detail to set up Gulp for your application, so Let’s get started from the very beginning.

Installing Node JS

To make use of any build tool, we’d require to have Node installed in our system. Now to install Node, head over to https://nodejs.org/en/download/and download and install your respective build as per your OS (Operating System). Installing Node also includes NPM within, which is Node’s Package Manager. We will look how it works later on this article when we install Gulp and all of it Plugins.

Testing Node and NPM

If you’re familiar with Command-line interface before, you can skip this step.

Like I mentioned in the beginning, I’ve assumed that you might not be familiar of using Command-line interface before, which you can understand as your Terminal in OSX/ Linux and your Command Prompt in Windows. While there are some really useful tools that make use of command-line interface, such as: Git, Gulp, Sass, Composer etc.

Also Read: Mean stack Interview Questions

You have now successfully installed Node in your system, but how should you test it, whether if it installed perfectly. Well, its simple, open your Command-line interface and type:

$ node -v

and to check whether NPM is working fine,

$ npm -v

These line of commands should return the version numbers on the next line. If you get any errors while executing these commands, then there must be some issues while installing, so go back to the previous step and install it again.

Initiate NPM in your project’s Directory

I hope you must have dealt with Command-line environment well so far must be ready to move on to the next step.
Now let’s navigate to your working project directory, so that we can setup everything. As I’m working on a Windows machine, yours could be different, but that doesn’t make any difference at all, logic of the context remains the same.

C:\xampp\htdocs\myproject\

Once in your project directory, run the following command in your CLI to initiate package.json file, that will require all of your dependencies.

$ npm init

When you run this command, it will ask you some questions to setup your json file, these are totally optional and you can either leave them blank, they will inherit all the default values then,for example

name: <your package name>
version: <your package version >
description: <your package description>
Entry Point: <your entry js file>
test Command: <your package test command>
Git Repository: <your git repo >
Keywords: <basic keywords for your package>
Author: <package author name>
License: <your package license>

After all the information has been setup, you can see your package.json file with all the information you’ve entered.

The Principle Phase: Installing Gulp

Till now, we’ve seen how we can setup our Node and initiate our package manager in our project’s directory. This is now the time to install Gulp into our project’s directory.

$ npm install -g gulp

The above command will install gulp globally in your system, so that gulp command is accessible through out your system globally.
let’s understand what this command exactly does here,

npm install: It will install all the dependencies as in your package.json file.
-g: this flag means to install the package globally in your system.
gulp: this is the name of package to be installed.

Once your system finishes installing Gulp, do exactly as you’ve done for node and NPM by running the command,

$ gulp -v

If its installed perfectly into your system, you’ll see the Gulp version in the next line.
I’m hoping that you’ve managed to get along with me through this point easily. Let’s move to the next step and installing Gulp and its plugins for our development build.

$ npm install gulp --save-dev

As you might have noticed, both install commands have just a single difference here, the — save-dev flag. You may be wondering now what this flag does? Well this is simple enough, this flag tells the NPM to add the dependency to our devDependencies list in our package.json file.
Dependencies help us organize our packages in the development and production environments. For further details, you can check the official docs of NPM dependencies.

Ok, we’ve come far now, and quite closer to what we want to achieve here.

Gulp is now installed, we need to give it some instructions so that what tasks we’d need to perform with this Gulp package. Let’s first decide what we want to do with our scripts and style files. Let me tell you my approach of work.

Adding some more useful Plugins

Now, to get the Gulp up and running, we need to update our package.json file a bit. The best way to do so is to add the dependencies through our very own CLI tool. Here, we are adding up the very basics, so let’s get going.

gulp-concat
gulp-cssmin
gulp-rename
gulp-sass
gulp-uglify
streamqueue

Let’s first go through each of these plugins one by one

  • gulp-concat — concatenates and merge the source files into the defined file.
  • gulp-cssmin — minifies CSS using Gulp.
  • gulp-rename — provides simple files renaming methods.
  • gulp-sass — plugin for compiling scss files, you can skip if not using SASS compiler for your styles.
  • gulp-uglify — minify files using UglifyJS
  • streamqueue — compiles the source files one by one in order to preserve their content order. (NOTE: its an alternative approach for queuing up your src files).
$ npm install gulp-concat gulp-cssmin gulp-rename gulp-sass  gulp-uglify streamqueue --save-dev

Now, run the above command, let your Command-line install all these plugins one by one. After the install is complete, you can open up your package.json file again & see the changes made in your file. These dependencies will now be available to you in your project’s directory.

The Next Big Step: creating the Gulp file

Now that we have setup everything necessary. Create a file named gulpfile.js in your project’s root and start typing along, we will go step by step so nothing mix you up.

  • Requiring the dependencies
var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var concat = require(‘gulp-concat’);
var rename = require(‘gulp-rename’);
var uglify = require(‘gulp-uglify’);
var streamqueue = require(‘streamqueue’);
var cssmin = require(‘gulp-cssmin’);

Now we’ll setup gulp tasks one by one.Let’s start by our CSS files.

  • CSS Task
gulp.task(‘css’, function ()
{
 return gulp.src([‘css/app.css’,'css/base.css'])
 .pipe(cssmin())
 .pipe(concat(‘style.css’))
 .pipe(rename({suffix: ‘.min’})) //optional
 .pipe(gulp.dest(‘assets/css/’));
});

Don’t get confused here, let me explain you what happening here.
Assume that you have a CSS directory in your project root, which contains some .css files within, that becomes your src. In the next step we are minifying the src files using cssmin(). Next we concat the minified CSS into file named style.css and rename it with the suffix of .min. Lastly we specify the desired destination to put up this file. In my case, it’s assets/css/style.min.css. Simple enough? eh? Let’s move onto the JS Task.

  • JS task
gulp.task(‘js’, function ()
{
 return streamqueue({objectMode: true},
 gulp.src(‘libs/jquery.min.js’),
 gulp.src(‘libs/jquery.bxslider.min.js’),
 gulp.src(‘libs/pushy.js’),
 gulp.src(‘libs/bootstrap.min.js’),
 gulp.src(“libs/product-images.js”)
 )
 .pipe(concat(‘all.js’))
 .pipe(uglify())
 .pipe(gulp.dest(‘assets/js/’));
});

Now as you might have noticed, there we’ve used streamqueue() instead of just arraying out in gulp.src(). It does almost the same as we’ve previously done with the CSS task, this is considered as the alternative way to keep an ordered compilation of files. You can use either of these approach.
The one new plugin used here is uglify(), which will minify your compiled JavaScript code and put it in the designated path. In this case it’s assets/js/all.js

Now, in case if you wanted to have some Real-time magic that will perform all the changes to your compiled file while you made change in your code.
If yes, then you can add up this watcher Task into your gulpfile as well.

  • Watch Task
gulp.task(‘watch’, function ()
{
 gulp.watch(‘css/**/*.css’, [‘css’]);
 gulp.watch(‘libs/*.js’, [‘js’]);
});

Now we need a default task to end up our gulpfile, which is a must have in your gulpfile.

  • Default Task
gulp.task(‘default’, [‘css’, ‘js’, ‘watch’]);
  • Final Gulpfile

Now, Your final gulpfile.js should look like this

var gulp = require(‘gulp’);
var sass = require(‘gulp-sass’);
var concat = require(‘gulp-concat’);
var rename = require(‘gulp-rename’);
var uglify = require(‘gulp-uglify’);
var streamqueue = require(‘streamqueue’);
var cssmin = require(‘gulp-cssmin’);
gulp.task(‘css’, function ()
{
return gulp.src([‘css/app.css’,'css/base.css'])
.pipe(cssmin())
.pipe(concat(‘style.css’))
.pipe(rename({suffix: ‘.min’})) //optional
.pipe(gulp.dest(‘assets/css/’));
});
gulp.task(‘js’, function ()
{
return streamqueue({objectMode: true},
gulp.src(‘libs/jquery.min.js’),
gulp.src(‘libs/jquery.bxslider.min.js’),
gulp.src(‘libs/pushy.js’),
gulp.src(‘libs/bootstrap.min.js’),
gulp.src(“libs/product-images.js”)
)
.pipe(concat(‘all.js’))
.pipe(uglify())
.pipe(gulp.dest(‘assets/js/’));
});
gulp.task(‘watch’, function ()
{
gulp.watch(‘css/**/*.css’, [‘css’]);
gulp.watch(‘libs/*.js’, [‘js’]);
});
gulp.task(‘default’, [‘css’, ‘js’, ‘watch’]);

If you’ve made the changes, then it’s time to move on and test out how this Gulp actually does make your life easier.

 

Open up your CLI and run the following command in your project’s root, you’ll see the tasks starting and then ending.

 

 $ gulp

Alternatively, you can also run all of the Tasks separately.

$ gulp css
$ gulp js
$ gulp watch

Now head over to your file directories, you should see your minified files at the designated paths. If not then follow the steps again carefully.

Gist File

You can check out this gist for a starter gulp file ready for your project.

Conclusion

Now you just need to include these single piece of files into your Headers to load all the assets.

I would recommend you to make this your practice in every single project, it’ll just take maximum of 5 minutes of your time but saves you a lot later on.

I hope you guys have enjoyed learning through this process of automating up your styles and scripts into more brief manner.
If you liked my article, take time to like it or leave me a comment. You can also follow me on Twitter.

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.