Introduction To Gulp JS

What is gulp js?

Gulp js is task runner

Meaning it is a program that can execute tasks based on specific criteria. Common usages are to set up a task that runs everytime a certain file is changed (or group of files) so you don't have to explicitly recompile every time, or to restart a server every time you restart the database.

How gulp works

  • node streams(Streams are objects that let you read data from a source or write data to a destination in continuous fashion)

  • pipeline/.pipe() - files not affected until task accomplished - single purpose plugins

  • code over configuration it value writing of code set on rules to be followed

For more check gupjs docs

Installing gulp js

For us to install gulp we need nodejs and node package manager

What is nodejs you ask

"Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a browser.", Nodejs official docs

1
$ npm install --global gulp-cli

Gulp has four top level functions:

  • Gulp.task - used to define a function to perform specific task

  • Gulp.src - points the source directory where files to manipulated reside which is conventionally know as the src.This in most case the working dir.

  • Gulp.dest - point to folder where final files are stored after manipulation by convention it is ussually known as dist or public .

  • Gulp.watch - watches for any file changes on src for files on the pipeline and automatically changes the the file's equivalent in the dist/public equivalent depending on the pipe functions

Working with Gulp

Let us create a our project gulpTrial

1
2
3
$ mkdir gulpTrial
$ cd gulpTrial
$ mkdir src 

run the following prompt in gulpTrial dir to create a depedency file package.json answering the question appropriately

1
$ npm init
1
$ npm install --save-dev gulp

Let us perform a simple of logging a message

Inside src directory create a file gulpfile.js whose content are like so:

1
2
3
4
5
const gulp = require("gulp");

gulp.task("message", function(){
    return console.log("Hello world gulp ...");
});

On terminal from your working directory(gulpTrial) run

1
$ gulp message

You should see when the pipeline starting i.e starting message , Hello world gulp ... and Finished message

If you want to run by default with specifying the aurgement you replace the string "message" by "default" like so:

gulpjsfile.js

1
2
3
4
5
const gulp = require("gulp");

gulp.task("default", function(){
    return console.log("Hello world gulp ...");
});

Now run

1
$ gulp 

Gulp can do more than just logging messages, let us move a file from our working directory(src) to its production equivalent(dist)

Let us say we are working on a website and we have created html files about.html and contact.html whose content are like so:

about.html

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
    <title>about</title>
</head>
<body>
<p> This is all about gulpjs demo now serious</p>
</body>
</html>
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
    <title>contact</title>
</head>
<body>
<p> You want to know gulp head here</p>
</body>
</html>

Create the above file on your src folder with their content.

Add this on gulpfile.js just below the the "default" task like so:

gulpjsfile.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//..
//.. "default" task

// copyHtml files

gulp.task("copyHtml", function(){
    gulp.src("src/*.html")
    .pipe(gulp.dest("public"));

});

In this file we have created a task "copyHtml" which will work will all file with .html(*html) from src directory and move them to public which will be automatically created Now run

1
$ gulp copyHtml

Take alook at your directory structure you notice public folder has been created and in it two files.

Exercise

  • Delete the public folder and tweak our "copyHtml" task to move create public directory and move content of src with .html extension to public when you run gulp

I don't want you to see gulp has a file mover or console logger so let us dig deep into it superior power

Let us it minify the images, make image smaller in size

We will use gulp-imagemin plugin

Let install it as dev(development) depedency.Like so:

Run this on your terminal on the working dir(gulpTrial)

1
$ npm install --save-dev gulp-imagemin

create an images directory inside src , on the created directory(images)add your favorite images files.

Add the following code to gulpfile.js

1
2
3
4
5
6
7
8
//..above "default" task
const imagemin = require('gulp-imagemin');
//..below "copyHtml" task
gulp.task('imageMin', () =>
    gulp.src('src/images/*')
        .pipe(imagemin())
        .pipe(gulp.dest('public/images'))
);

Checkout the file size of minified images and the once in src/images dir

Exercise

  • create a src/javascript dir, inside create a js file, create a gulp task ("minifyJs") which minifies any file with .js extension from src/javascript to public/javascript use gulp-uglify plugin.

  • create a src/sass dir, inside create a js file, create a gulp task ("createCss") which minifies any file with .scss from src/sass to public/css use gulp-sass.Ensure it logs errors incase of any.

Creating a pipeline

We said gulp work in pipeline what exactly do that mean, the output of one function act as aurguement of the other for instance the say.There is function which find sum and then the other finds the square of the sum.the square function will take output of sum as its aurguement.

We will create pipeline that checks for all .js files in the src/javascriptdir concatinate them into main.js uglify it and then tranfer it to public/javascript/main.js file.Add this code to your gulpFile

1
2
3
4
5
6
gulp.task('jsscripts', function(){
  gulp.src('src/javascript/*.js')
      .pipe(concat('main.js'))
      .pipe(uglify())
      .pipe(gulp.dest('public/javascript'));
});
1
$ gulp jsscripts

And take a look at the public/javascript/main.js

Gulp watch

Just like it name suggests it watches for any changes made of working directory(src) files and update their public contepart.

I am making an assumption you already have created .js files in the src/javascript/ during above exercise

Let us watch over changes made on files in src/javascript/ with .js exentsion

We the watch task the files to watch and the task

1
2
3
gulp.task('watch', function(){
    gulp.watch('src/javascript/*.js', ['jsscripts']);
}

Run

1
$ gulp watch

Try making changes in your js file an take alook at public/javascript/main.js

Note we only work on the src(our working directory) or whatever name you give and never in dist/public(our production directory)