Get started with Gulp.js
Repetitive tasks, such as compiling SASS to CSS, concatenating and minifying CSS and Javascript code, compressing images, transpiling ES6 to ES5 cross-browser compatible code and deploying production-ready files, take up much of a developer’s time. In reality, these spend precious little time coding compared to the sum of these time consuming tasks that need to be repeated everytime a change is made.
Thankfully, even though optimizing our website assets is certainly not the fun part of the development process, it can become much more simple and hassle-free with the right tools. This is where build tools come in. These life saving tools help us automate those tedious common tasks that eat our productivity and optimize our development workflow. Think of them like your mother back in the day, when she used to prepare your breakfast so you didn’t get late to that exam you were having monday morning.
What is Gulp and why use it?
Gulp.js is an open-source build tool used to automate and thus enhance the development workflow. It is built on Node.js and it’s tasks are written in Javascript, making it the perfect task runner for the modern javascript-loving front end developer.
In their website, they claim to be “a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something”. It can be used, for example, to compile SASS, parse templates and lint Javascript or CSS, and, better yet, in a language that you are probably already very familiar with.
What other build tools do we have out there?
Build tools have been around for a while already. Grunt was very popular around 2014 and it has a very large plugin library that allow you to do a number of different tasks. However, it’s approach is very different from Gulp, which has plugins to perform small individual tasks.
In general, Gulp makes the configuring process far more simple in comparison with Grunt. A simple Grunt task would require a large object as opposed to a few lines of code with Gulp.
Gulp really brings a few improvements to the build tools scene. However, of course, it is not perfect itself and other more recent build tools are getting attention within the developer community — take the example of Webpack or Brunch.
Getting Gulp up and running
Setting up Gulp is a fast and simple process, but before you start, make sure to have Node.js installed on your machine. Once you got it, you’re ready to follow along the following steps.
First, install Gulp CLI globally. This allows the Gulp command to be run from any directory.
npm install gulp-cli -g
Next, install Gulp locally on your project’s directory. This installs Gulp as a development dependency for your project and will update the package.jsonfile accordingly.
npm install gulp --save-dev
Note that development dependencies are not installed when the NODE_ENVvariable is set to production. In this case, Gulp can be installed as an application dependency, by running the following.
npm install gulp --save
The Gulpfile
Alright, Gulp is ready to go. Simple, isn't it? All we have to do now is to setup the gulpfile.js. This is a configuration file, created on the root of our project’s directory.
However, this file will not do something simply because we have a strong willpower. We need to specify behavior instructions for it to understand what tasks we want Gulp to perform for us.
Gulp tasks!
As I have said before, Gulp will do nothing on its own. To explore this tool’s potential, we have to install plugins and write tasks that use those plugins.
Writing a Gulp task is fairly simple. It only takes two attributes: the task’s name and the function that will be run when this task is called. See below.
gulp.task("hello", function() {
console.log("Hello World!");
});
So, running gulp hello will print “Hello World!” to the console.
Great! We have written our first Gulp task, even though this one doesn't really bring much workflow optimization. For that, we’ll have to use one of the thousands of existing plugins (we can also write a plugin ourselves, but it’s almost certain that there is already one that performs the task we need).
To search for plugins, we can go directly to Gulp’s library or we can search the NPM Package Repository.
To install the plugins, we run npm install just how we do to install Gulp.
Before we dive right in, it’s useful to note that Gulp only has 5 methods: .task, .watch, .run, .src and .dest.
Plugin calls are made with a .pipe between the .src and the .dest.
Let’s take the following gulpfile.js as an example.
// Include Gulp and the necessary plugins
var gulp = require('gulp'),
sass = require('gulp-sass'),
imagemin = require("gulp-imagemin"),
cache = require("gulp-cache");
// Task to compile SASS
gulp.task('sass', function() {
return gulp.src('scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'));
});
// Task to minify images
gulp.task('images', function() {
return gulp.src('images/**/*.+(png|jpg|gif|svg)')
.pipe(cache(imagemin()))
.pipe(gulp.dest('dist/images'));
});
// Watching files for changes
gulp.task('watch', function() {
gulp.watch('scss/*.scss', ['sass']);
gulp.watch('images/**/*.+(png|jpg|gif|svg)', ['images']);
});
// Default task
gulp.task('default', ['sass', 'images', 'watch']);
Worry not — it really is quite as simple as it looks and we will keep it just as simple for this article! Gulp does allow us, nevertheless, to get our hands dirty in complexity as long as we need it.
Alright, let’s break this into pieces.
First, we require Gulp and all the other plugins that are needed for our task execution.
// Include Gulp and the necessary plugins
var gulp = require('gulp'),
sass = require('gulp-sass'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename');
Now we’re ready for tasks, let’s start by creating one to compile and our SASS code to CSS. This task will grab any .scss file located in the scssfolder, compile it into CSS and store in on the dist/css folder. Note the use of the .src and .dest methods and the plugin call using .pipe.
// Task to compile SASS
gulp.task('sass', function() {
return gulp.src('scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'));
});
Now, let’s define a task to minify our images. This will grab any file with .png, .jpg, .gif or .svg format in any folder inside the imagesdirectory, check if it has already been cached (if so, it will not be passed downstream) and store it on the dist/images folder.
// Task to minify images
gulp.task("images", function() {
return gulp.src("images/**/*.+(png|jpg|gif|svg)")
.pipe(cache(imagemin()))
.pipe(gulp.dest("dist/images"))
});
Now it’s time for the watch task, which will keep an eye on the changes we do to our files in order to run the needed tasks automatically. For example, everytime we make changes to our SASS files, this task will automatically run the task to compile it to CSS, saving us precious time. To write it, we make use of the .watch method, which takes in two attributes — the files to look for changes and the tasks to run.
// Watching files for changes
gulp.task('watch', function() {
gulp.watch('scss/*.scss', ['sass']);
gulp.watch('images/**/*.+(png|jpg|gif|svg)', ['images']);
});
Lastly, we define the default task for Gulp. This is the task acting when we run the gulp command. In this case, we want our default task to run sass, images tasks, to update our built files, and then the watch task, in order to watch for file changes.
// Default task
gulp.task('default', ['sass', 'images', 'watch']);
Running Gulp
Perfect! Now Gulp is ready to run.
We can either run gulp to run the default task or gulp [task] to run a single specific task.
Now this is a very simple way to use Gulp and it does not explore it’s full potential (by far). But this is definitely a tool worth knowing as it can truly improve your workflow:
- It has a huge plugin base for endless purposes.
- Configuration is really simple and can be adapted for use in other projects.
- Simplification!!
If you want to see a bit of what Gulp has to offer, take a look at some of the most incredible plugins that you definitely can’t miss:
- gulp-load-plugins, loads all the plugins you need without the need to use a require statement.
- browsersync, refreshes your page on every change you make.
- sitespeed, super useful for performance testing.
- gulp-size, displays file sizes.
- gulp-plumber, error handling to stop Gulp from stopping when there’s a failure.
Being self-taught is a journey of exploration and discovering build tools really changed my workflow for the best. Spending a few hours getting a good understanding of these will result in a huge improvement for your future endeavors.
Experimenting with Gulp really made me fall for it’s simplicity, which is something you might also be looking for as a learner. I just can’t recommend it enough.
I really hope you get your hands dirty after reading this. You will love it.
Originally posted at Medium.