A Simple Javascript Tutorial On Gulp JS Automation

Whenever you hear the word automation in IT or among developers nine out of ten times they will be referring to python, If you are like me, a js developer you will feel left out. This article will give you a simple javascript tutorial on Gulp JS to automate almost anything in web development.

What is Gulpjs?

GulpJS is an automation toolkit for js, you can do things like compile, create or move files, minify code ( example: js, HTML, CSS), optimize images, and many more. You can even create your own CLI for your js project ( yes, just like angular-cli ).

Where to use Gulpjs?

  • If your project includes js libraries like jquery or alpine ( check for a tutorial here ), GulpJs can help you in many ways like minification, image optimization etcetera.
  • GulpJS can be really handy in React projects, as it doesn’t come with a rich CLI-like angular.
  • If your project includes SASS, you can configure gulp to compile it to CSS, even watch for changes in files, and auto-compile.
  • You can also serve your project as an HTTP or HTTPS site using gulp.
  • GulpJS has vast plugin support through npm, so personally, the use cases of gulp are your imagination.

Basic concepts:

In this section, we will see the basic concepts of GulpJS with an example, and later we will use these in a sample project ( simple calculator app ).

Installation:

We have to install both gulp-cli and gulp.

npm install --global gulp-cli

Create a folder and type the following commands.

npm init -y
npm install --save-dev gulp

If successfully installed giving the command gulp --version in a terminal will give you a result similar to the below screenshot.

javascript tutorial - version output

version output

All the gulp code should go inside the gulp.js file in a project folder.

Note: gulp.js file should be in the root folder.

Tasks:

The task is a simple js function that contains code to handle files, there are two types of tasks in GulpJS they are as follows.

public: these tasks can be run directly from the terminal using gulp <task name>

private: these cannot be called from the command line but will be executed inside the gulp file.

Example:

javascript tutorial - sample task

sample task

In the above example, We have declared a function called sampleTask and exported it by default. For the sake of simplicity I have just consoled ‘hii’ and called cb at the end ( we need to call cb because gulp doesn’t know when to finish a particular task. We can also return promises in case of async tasks ). When you export a task by default. You can run your code using the gulp command.

In your terminal entering the gulp command will result.

javascript tutorial - execution result

execution result

We can see logs about the execution, when the default function started executing, the duration of the task, and our ‘hii’ console log.

The sampleTask function is a public function so running gulp sampleTask, gives the same result.

Possible errors:

When you don’t call cb ( callback from the task ), you will see the following error. You should call cb in order to tell gulp that this is the end of a particular task.

javascript tutorial - error resut

error result

You can see our ‘hii’ printed but the task was not successful, most of the gulp errors are so descriptive that you can understand them directly.

composition methods ( private functions ):

Composition methods allow you to configure how the tasks should run. There are two composite methods, they are as follows.

series: as the name suggests tasks inside this method will execute one by one.

parallel: tasks run in parallel.

Example:

javascript tutorial - composite method example

composite method example

  • Here we see two tasks sampleTask and sampleTask2, printing hii and hii2 respectively.
  • I have delayed the sampleTask function execution by 100ms purposely to see how it will execute on both series and parallel methods.
  • And we have the default function executing our two functions in series ( one by one ).

Result:

javascript tutorial - composite method result

series composite method result

In the above screenshot you can see that even though the sampleTask task 100ms to complete, it is executed first and then sampleTask2. This is because we have used gulp.series method

Let’s see what happens when we substitute series with parallel function.

javascript tutorial - parallel composite method result

parallel composite method result

You might have guessed, that now sampleTask2 task is executed first and then sampleTask. This is because both the tasks are running in parallel and are not dependent on each other.

Possible errors:

You have to be careful when calling the cb function in the above example on sampleTask, say if you have called cb() outside the setTimeout function, then the result will always be ‘hii2’ printing first and ‘hii’ printing second.

Src, dest, pipe:

 Now create a sample index.html file with a sample code. src method of gulp will take in a file path as a parameter and pipes are used to alter files ( example: compress, minify). The altered file can be created at a specific path using the dest method.

Example:

javascript tutorial - sample code

sample code

In the above example, we have sampleTask that returns a weird line, we will break that down.

  • gulp.src(‘index.html’) takes the index.html file as input, if your index.html is located in some other folder, say public, you have to give the respective path, for example, ‘public/index.html’.
  • Next line we have a .pipe method that takes the output of the previous method and passes it down the function, in this case, gulp.dest(‘output/’).
  • gulp.dest(‘output/’) outputs our index.html file in a folder called output.
  • Note that we did not use the cb() function here as gulp.src is a promise, we just need to return this method and gulp will take care of the rest.

Note: For now our task does nothing to the index.html file, later on in this tutorial we will alter HTML and js files using the same methods.

Result:

Now if you run gulp in the terminal, you will see an output folder without the index.html file.

Possible errors:

One possible error is that if you are on a Linux machine and don’t have the write permission on the directory you will be thrown an error, in this case, change the folder’s permission to write and read ( reference link: https://www.pluralsight.com/blog/it-ops/linux-file-permissions ).

Globs:

Globs are a way to reference files in GulpJs. I will list out the important ones down here, but there are many concepts and ways ( reference link: https://gulpjs.com/docs/en/getting-started/explaining-globs ).

  • *.html means that reference all files ending with HTML extension
  • public/**/*.html means match all the HTML files inside a public folder, including nested directories ( any level ), example: this will match public/index.html, public/folder1/index.html, public/folder1/../index.html.
  • ! in front of any path will exclude that file(s) from the tasks.
javascript tutorial - sample gulp task - including glob

sample gulp task – including glob

In the above example, we refer to all the HTML files in the current directory. 

For testing create multiple HTML files in the same directory.

Result:

If you run gulp in the terminal, you will see an output folder containing all the HTML files in the current directory.

Working with plugins:

The main advantage of using gulp is that it has huge plugin support, you can do many things as mentioned before. In this section, we will see a simple code to implement plugins in GulpJS.

Here we rename our HTML files using the gulp-rename plugin and store them in the output folder. First, install the plugin using the following command.

npm i gulp-rename
javascript tutorial - the task to rename the HTML file

the task to rename the HTML file

In the above code, we see an extra pipe that takes in a rename function with a JSON specifying the extension name, the configurations are specific to the plugins and those details can be found in their respective GitHub or npm pages.

Result:

Running the command gulp will create a folder called output and inside the folder, you can find a file called index.min.html ( renamed file ).

Watching files:

GulpJS can watch for changes in files and execute tasks accordingly. In this section, we will watch our sample HTML file and execute sampleTask when our HTML file changes.

javascript tutorial - task with watching

task with watching

In the above code, we have added an additional function called watchFile, which contains gulp.watch(‘*.html’, sampleTask), this line means that gulp listens for changes from all HTML files in the current directory and will execute the sampleTask function on changes.

Result:

Running gulp will start the gulp watching files.

javascript tutorial - result watching

result watching

Now try changing the HTML file. You can see the gulp executing sampleTask.

javascript tutorial - result watching with results

result watching with results

If you open the index.min.html inside the output folder, you will see the changes you made.

Note: by default gulp.watch will not execute the given task initially, for this to work you have to pass { ignoreInitial: false } as an option. Now after this your code should look like

gulp.watch('*.html',{ ignoreInitial: false },sampleTask).

Calculator app:

Here we have a simple calculator app, we will use GulpJS for the following tasks.

  • Transcomiple es6 code and bundle using the webpack-stream plugin.
  • Uglify js code using the gulp-uglify plugin.
  • Minify HTML code using gulp-html-minifier plugin.
  • Clear old build files using gulp-clean.

To run:

  • npm i to install all the packages.
  • npm run build to build once.
  • npm run watch to watch for changes in js and HTML code.

GitHub repository:  https://github.com/kishork2120/calculator-app-gulp.

Special shoutout to string-math, a cool npm library to convert string to math expression.

Have fun coding !!

Leave a Reply

Your email address will not be published.

Pin It on Pinterest