Automate The Mundane Stuff With Gulp 4
At Edraak, we are continually searching for ways to automate repetitive, mundane tasks be it compiling SCSS/SASS, moving/renaming files, cleaning/minifying JavaScript/CSS, or even running Bash scripts! Doing so not only enhances the developer’s productivity and workflow, but also saves them valuable time and effort.
One toolkit that has stood out for its effectiveness isgulp
designed to
automate and enhance your workflow.
In this blog post, I will introduce you to gulp and the function of the gulpfile.js
file, which you may have come across during a previous project (whether on the frontend or backend). Plus, explaining the different ways you could use this toolkit and guiding you through a simple introductory tutorial highlighting its various uses.
Why use gulp?
Automation
- Compiling SCSS/SASS
- Compiling TypeScript
- Cleaning and minifying JS/CSS code
- Watching files to reload the browser and re-compiling TS/CSS
- Optimizing Images to boost the website loading speed
Easily integration with other tools:
- Integrate tools and libraries with gulp to enrich your development workflow ( like Browsersync, Babel, or Webpack)
To be clear, gulp only automates and organizes the tools responsible for the above functions. Some tools compile SCSS/SASS like node-sass
, Typescript like tsc
, and JavaScript into older versions compatible with any browser like Babel
.
Introductory tutorial
Before you begin, you must install Nodejs and NPM since gulp runs in a node environment
- Start by forming the above folder structure.
gulpfile.js
in the root of our directory where we will enter functions for gulp to execute.- The src folder is where the JS/SCSS resides.
package.json
andpackage-lock.json
will be added after we runnpm init -y
on this directory allowing us to use any NPM package here.
Initializing the NPM project and installing gulp
In the above folder, you must run the following commands:
npm init -y
: This allows the use of the NPM packages. The-y
flag is written to answer “yes” to all the questions asked by NPM since they are not vital in our current context.npm install gulp -D
: This installs gulp locally, while the-D
flag turns this package into a development dependency (i.e a pacakge for the developer to interact with). You might have also noticed a gulp-cli that you can install globally. However, I prefer installing gulp locally and calling it using NPM scripts. This facilitates changing the gulp version and limits the number of tools to be installed prior to developing.- The
npm init -y
command creates a file titledpackage.json
. You must change itsscripts
property to match the below.
{
"scripts": {
"dev": "gulp"
}
}
Next, run npm run dev
to launch gulp from the node_modules
folder we had created after installing the first package using NPM.
Gulp tasks
Gulp tasks are asynchronous functions that are executed in parallel or series. But first, we must define them within the gulpfile.js
file which is in the root of our directory.
However, since gulp taks are asynchronous, we can execute them in parallel or in series.
Creating a gulp task that compiles SCSS into CSS
In the gulpfiles.js
, we must export a default function (gulp task) so that upon running npm run dev
, gulp will be triggered and launch the default exported functions from the gulpfiles.js
.
PS: At the end of this article, you will find the code as a GitHub gist.
Now, when you run npm run dev
you will see the following output in the terminal:
Our tasks will only invoke one function called cb
(call-back). This one function is passed to all gulp tasks so they can inform gulp when they have finished.
Another way to do this is to return a promise or stream (read more about this here).
The series
function imported from gulp tasks can perform as many functions as you need, but sequentially, executing one before moving on to the next.
On the other hand theparallel
function runs all gulp tasks passed to it simultaneously.
Compiling SCSS to CSS
To compile SCSS to CSS, we need to use node-sass
. Which requires a pacakge called gulp-sass
that intergrates it with gulp.
To install them write the following command npm install node-sass gulp-sass glob -D
then go to your gulpfile.js
to add logic to it. I also installed a package called glob
which grnts access to all the file paths that match a mini-match expression as an array. We’ll get to that in a bit.
Explaining the compileSCSS
function:
- Import the
scss
module fromgulp-sass
which usesnode-sass
to compile SCSS/SASS and integrates it with gulp. - Getting the
sync
function from glob which after giving it a mini-match expression will return an array of matched file paths. In turn the file paths will serve as the input to gulp. In our case, place all the files inside that end with.scss
insrc/scss
no matter what they are called (*.scss)
or on which level they are nested**/*.scss
. - Impoert the join function from the built-in package in Nodejs called
path
. It basically joins strings to produce a file path. You can contact strings manually but I believe using this function is better.
To summarize this, we are using the src
function from gulp which tells it to use all the files returned as paths from the sync
function as an input to process them (in our case compile them.) After this (which returns a stream) we will call .pipe
on these files and pass them as a stream to the sass
module to be compiled.
.on('error')
is an event listener that calls thesass.logError
function if any error occurs in the output, allowing us to debug them, Interestingly, this is actually one of the events in streams, which by the way are returened bysrc and pipe
.
After the sass
module compiles our SCSS files, they will be passed as a stream to the dest
function imported from gulp that will place the output from this stream into src/dist
.
Now, you can run npm run dev
You can also look at our src/dist
folder (don’t forget to put some SCSS to get a final compilation).
Cleaning and minifying our compiled CSS
Once you’ve understood the previous section, you’ll be good to go! if not, I will guide some more to help clear things up.
Start by installing a package called gulp-clean-css
, which integrates clean-css
with gulp.
Explaining the minifyCSS
function:
You may notice that the two functions are pretty similar. Here, our src
is all the files that end with .css
in the src/dist
folder that we pass to the cleanCSS
function. Once this step is complete, we will return them to the src/dist
folder which will override the compiled CSS files with the new, compiled and cleaned files.
You may have noticed that I’m not accepting a call-back function for the compileSCSS and minifyCSS tasks because you are now using streams, which you want to return to let gulp knows that these tasks have finished. If you are using
parallel
tasks, you won’t face unexpected behaviors.
Final thoughts
This is a small introduction to gulp, and if you understood it well, you’ll be able to maintain and improve any gulp tasks on your own. However, you need to remember a few things:
- Read the docs here. They explain how gulp works very well.
- If you want to compile typescript you need to search for a package that integrates the typescript compiler with gulp. The same applies to (Babel, Webpack, etc).
If you’re wondering whether gulp is popular, here’s a simple graph illustrating its usage against other tools.
Although it’s not as popular as webpack, gulp can be used for any basic frontend application or for automating repetitive tasks on the backend.
What about compiling JavaScript with gulp? Let me show you some simple gulp tasks that compile js usingBabel
and the parallel
gulp function.
PS: This code contains the code for compiling and minifying JS/SCSS
Conclusion
I hope you found this useful! If you have any questions, please leave a comment. Your thoughts are highly appreciated.