Official website for Linux User & Developer
FOLLOW US ON:
Jun
17

Optimise your web code with Gulp.js

Posted by Rob Zwetsloot

Explore the many benefits of using the Gulp.js task runner in your web projects to help streamline your workflow and optimise your code

The chances are quite high that during any one web project, you have dealt with or written more than one CSS or JavaScript file. These have network overheads when we end up delivering them to the end user and can cause latency and loading issues if they are too large. They may also not be as well optimised as they could be, perhaps leading to console errors or slow performance in general.

Enter Gulp.js, a free open source JavaScript task runner powered by Node.js, which has quickly gained traction in the web development community as a fast, powerful alternative to existing task runners on the market. But what are the benefits of creating and implementing a task runner tool into your workflow?

Using a task runner you can make the most of CSS preprocessors such as SASS or LESS to streamline how you write stylesheets, as well as coffeescript for your JavaScript files. The task runner can compile these into the desired formats for final delivery. It can then iterate over your directories and combine preselected files into one larger file, minifying it in the process, while still keeping an unminified version.

The additional benefit of a task runner is that it will watch all of your directories and files and only run selected tasks when a file or structure has changed. This removes the necessity to manually run any task each time an update has been made.

Let’s also add in the ability to run code validation and tests against your code, automatically run as you save the file and now you should start to see the real power behind implementing a task runner procedure into your web projects.

If you have some prior exposure to JavaScript, you can get started with Gulp.js in a matter of moments and add it into your projects quickly. Let’s have a look at how easy it is to work with and create your own task definitions.

Set up your project now
Set up your project now

Step-by-step

Step 01 Install Node

Before you can begin exploring Gulp.js, you will first need to satisfy the most important requirement, which is to install Node. Simply head over to nodejs.org and download and install the application onto your development machine. This is all a very quick and painless process, taking no time at all.

Step 02 Install Gulp

With Node installed, you now have access to the Node Package Manager (npm), which we will use to install Gulp as a global package onto our system. With your Terminal or command prompt window open, use the git repository (github.com/gulpjs/gulp) to install Gulp on your system.

Step 03 Save as dependency

Now you will need to create a ‘package. json’ file within your project directory. A skeleton file can be created for you using the npm init command from the Terminal. Once created, you will need to install Gulp as a dev dependency for your project, which will update the package.json file for you.

Step 04 Ready to gulp

After the Node Package Manager has obtained and installed Gulp as a dev dependency, the reference to the dependency is also automatically added to the package.json file as a requirement. Any user or development machine with shared access to this json file can install the same dependencies quickly and easily.

Step 05 Install chosen plug-ins

As with any Gulp project, you will first be required to install your plug-ins as dev dependencies to have them automatically added to the ‘package.json’ file. You are also able to install multiple plug-ins in one command – just make sure to use the –save- dev command. Install the gulp-load-plugins plug-in as well, which will help manage the references when we code.

npm install gulp-concat gulp-jshint gulp-bump gulp-load-plugins--save-dev

Step 06 Reading package contents

The top of Gulpfile.js requires the core Gulp library as usual. Directly below this, instead of calling in each plug-in individually we can load them dynamically by using just the gulp-load-plugins library. This will read the dependencies in the package.json file and inject each of them for us.

var gulp = require(‘gulp’);
var gulpLoadPlugins = require(‘gulp- load-plugins’);
var plugins = gulpLoadPlugins();

Step 07 Adjust references

The dynamically loaded plug-ins have been assigned and required into the project via the gulp-load-plugins extension. They will now be available for use in your Gulpfile.js by referencing them from the plug-ins object variable. For example, any reference to concat() would become plugins.concat().

gulp.task(‘lint’, function() {
return gulp.src(‘js/*.js’).pipe(plugins.jshint()).pipe(plugins.jshint.reporter(‘default’));});

Step 08 Further options

This plug-in has a number of configuration options which you can pass into the gulpLoadPlugins() method. These include which file to read, which keys in the selected file are read to obtain the plug-in name, and whether or not the plug-ins are lazy loaded. For more information, make sure you check out the official repository page at github.com/ jackfranklin/gulp-load-plugins.

gulpLoadPlugins({
   pattern: “gulp-*”,
   config: “package.json”,
   scope: [“devDependencies”],
   replaceString: “gulp-”,
   camelize: true,
   lazy: true,
});

Apply Gulp to a project

Step 09 Create gulpfile.js

When you run Gulp via the command line, it will look for the existence of the ‘gulpfile.js’ file. This file informs the task runner which plug-ins to load and defines the available tasks to perform as well as setting the order of any chained tasks. Create Gulpfile.js in the project root and ensure it requires Gulp at the very top.

var gulp = require(‘gulp’);

Step 10 Reference plug-ins

Any plug-ins that have been installed as dev dependencies and are to be used within the Gulp process will need to be defined and made accessible. To do so, simply require each plug-in by name and assign to a variable that can be called and used throughout the configuration.

var jshint = require(‘gulp-jshint’);
var concat = require(‘gulp-concat’);
var uglify = require(‘gulp-uglify’);
var rename = require(‘gulp-rename’);
var header = require(‘gulp-header’);

Step 11 Code linting

The first task will check any JavaScript code for errors by passing it through the default linting engine. Simply register the task by providing a name and the associating function. Here the source directory is set and all files within it will be piped to the jshint() method for parsing and validation.

gulp.task(‘lint’, function()
{
   return gulp.src(‘js/*.js’)

      .pipe(jshint())

      .pipe(jshint.reporter(‘default’));
});

Step 12 Minification and concatenation

To streamline network resources let’s also make sure any JavaScript files are combined into one file and then a minified version of each created. Once more, set the source directory from which to pull the files, which are then concatenated and injected with a header value before being placed into the destination directory.

gulp.task(‘scripts’, function() {
   var headerValue = “Evaluated by gulp.\n”;
   return gulp.src(‘js/*.js’)
      .pipe(concat(‘combined.js’))
      .pipe(header(headerValue))
      .pipe(gulp.dest(‘dist’))
      .pipe(rename(‘combined.min.js’))
      .pipe(uglify())
      .pipe(header(headerValue))
      .pipe(gulp.dest(‘dist’));
});

Step 13 Always watching

One major benefit of any task runner is having the ability to watch a directory of files and to be able to react to any changes that are made to them. Here another task is created to manage this very simple but powerful aspect of the workflow. Once a change is detected, Gulp will pass those files through to the lint and scripts methods for processing.

gulp.task(‘watch’, function() {
   gulp.watch(‘js/*.js’, [‘lint’, ‘scripts’]);
});

Step 14 Default tasks

When starting Gulp from the command line you can optionally pass in the name of the task to run. If this is omitted, Gulp will run a default task if one is available. You can easily ask Gulp to run a series of tasks in order as part of the default task.

gulp.task(‘default’, [‘lint’, ‘scripts’, ‘watch’]);

Gulp plug-ins

Step 15 Plug-in repository

While Gulp doesn’t have a plug-in repository, a client-side application has been created that reads from the Node Package Manager library and filters plug-ins that are available for Gulp. This is a fantastic resource to see exactly what you can implement into your task workflow.

Step 16 Details and documentation

Each plug-in page within the NPM repository holds detailed documentation about the plug-in in question, the installation procedure and then some code examples for usage and implementation.

Step 17 No limits

There are no limits on how many plug- ins you can install into your Gulp process, saving them into your ‘package.json’ file or in a single request from the Terminal and the npm install command. Tailor your workflow task processes to suit your own preferences and your project requirements.

Step 18 Update plug-ins

Plug-ins can evolve as new features and bug fixes are added. You can update your installed dependencies easily using the Node Package Manager via the command line. Simply enter ‘npm update’ from the command line and keep your plug-ins up to date.

  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.