Getting started with Gulp.js from scratch

gulp

Let’s talk and think…

So, you are a front-end developer, right? Don’t you think we should optimize our repetitive tasks as much as possible? Well, I have good news for you; nowadays we have a vast amount of tools that make our life easier and happier… you don’t believe me, right? Continue reading then…

When we work in front-end projects, we usually do a set of tasks that are repeated frequently in all our projects, let’s see some examples:

  • Minifying JavaScript.
  • Compressing CSS files.
  • Compiling source files of pre-processors (LESS, Stylus, SASS/SCSS).
  • Optimizing images to reduce their sizes.
  • Validating JavaScript code (JSHint).
  • Transforming a language like TypeScript to JavaScript.
  • Execute a set of tests with your favorite Unit Testing Framework.
  • etc.
  • etc.

Well, if you want to automate this kind of tasks, my friend I have a great tool for you: Gulp.js.

javascript-logo

From my personal opinion, Gulp.js is one of the best task runners that we have currently; even compared with Grunt, because it is easier to learn and the logic, on my gosh! if you know something about pipes in GNU/Linux or UNIX, you will find Gulp.js as a blessing 🙂 its syntax is clear, pure JavaScript code, nothing really new to understand, piece of cake I promise you.

What do I need?

  1. Install Node.js for your operating system.
  2. After installing, verify the Node.js and NPM versions:
// Verify Node.js version in command line
node --version
➜ v0.10.23

// Verify NPM version in command line
npm --version
➜ 1.4.7

Let’s start

Console-128

First command you have to learn is the one related with the initialization of a project using the Node Packaged Modules (NPM). This instruction must be executed in the root directory of your project.

npm init

This command will create a file called package.json which contains all the configuration for your project; including the dependencies for development.

This file is the analogous to the pom.xml when working with Maven (JavaEE developers where are you?), or the composer.json when developing using PHP Composer (yes, the awesome Dependency Manager for PHP).

{
  "name": "econtinua",
  "version": "1.0.0",
  "description": "Un ejemplo completo con modernas herramientas para desarrollo frontend",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/alex-arriaga/fcc-buap-taller-frontend.git"
  },
  "author": "Alex Arriaga",
  "license": "GPL-3.0",
  "bugs": {
    "url": "https://github.com/alex-arriaga/fcc-buap-taller-frontend/issues"
  },
  "homepage": "https://github.com/alex-arriaga/fcc-buap-taller-frontend",
  "devDependencies": {
    "gulp": "^3.8.7",
    "gulp-concat": "^2.3.4",
    "gulp-imagemin": "^1.0.1",
    "gulp-less": "^1.3.5",
    "gulp-minify-css": "^0.3.7",
    "gulp-rename": "^1.2.0",
    "gulp-stylus": "^1.3.0",
    "gulp-uglify": "^0.3.2",
    "gulp-watch": "^0.6.9",
    "imagemin-pngcrush": "^0.1.0"
  }
}

Now, that you have your NPM ready, it is time for installing Gulp.js by using it; it is a good idea to have Gulp.js as  a global package, see the option -g in next line:

sudo npm install -g gulp

Ok, after installing it, let’s verify its version:

gulp -v

Once we have Gulp.js installed globally, it is time to create our configuration file; yes, it is another configuration file where we will specify all the tasks we want to run; either one by one  or in a set of them; this file is the famous: gulpfile.js

touch gulpfile.js

And put all these lines of code inside of it; these are our tasks:

/**
* File: gulpfile.js
* Author: Alex Arriaga (@alex_arriaga_m) - http://www.alex-arriaga.com
* Date: 26/Aug/2014
*/

var gulp 	= require('gulp');
var concat 	= require('gulp-concat');
var rename 	= require('gulp-rename');
var watch 	= require('gulp-watch');
var uglify 	= require('gulp-uglify');
var less 	= require('gulp-less');
var stylus = require('gulp-stylus');
var minifyCSS = require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var pngcrush = require('imagemin-pngcrush');

var baseDirDev = './dev/';
var baseDirJs = './dev/js/';
var baseDirCSS = './dev/css/';

var paths = {
	dev 	: './dev/',
	prod 	: './prod/',
	scripts : [baseDirJs + 'jquery-1.11.1.js', baseDirJs + 'js/bootstrap.js'],
	images 	: [baseDirDev +'img/*.jpg', baseDirDev +'img/*.png'],
	fonts	: 'fonts/*',
	less 	: 'less/*.less',
    stylus 	: 'stylus/*.styl',
	css 	: [baseDirCSS + 'bootstrap.css', baseDirCSS + 'econtinua.css', baseDirCSS + 'econtinua-responsive.css', baseDirCSS + 'font-awesome.css']
	// stylus 	: 'stylus/*.styl'
};

// This object contains parameters for minifying operation.
// Please, read more about it in this link: https://www.npmjs.org/package/gulp-minify-css
var minifyCSSOptions = {
	keepSpecialComments: 0,
	keepBreaks: false,
	debug: true
};
/*
// 1. Transform LESS file to CSS  (place CSS files into dev/css folder)
    gulp.task('less', function() {
        console.log("Running LESS task...");
        return gulp.src(paths.dev + paths.less)
        .pipe(less())
        .pipe(minifyCSS(minifyCSSOptions))
        .pipe(gulp.dest(paths.dev + 'css'));
    });
*/

// 1. Transform Stylus files to CSS  (place CSS files into dev/css folder)
    gulp.task('stylus', function() {
        console.log("Running Stylus task...");
        return gulp.src(paths.dev + paths.stylus)
            .pipe(stylus())
            .pipe(minifyCSS(minifyCSSOptions))
            .pipe(gulp.dest(paths.dev + 'css'));
    });

// 2. Compress CSS (it will run after 'stylus' task finishes
	gulp.task('compress-css',['stylus'], function() {
        console.log("Running compressing CSS task...");
		return gulp.src(paths.css)
			.pipe(concat('all-styles.css'))
			.pipe(gulp.dest(paths.prod + 'css'))
			.pipe(rename('all-styles.min.css'))
			.pipe(minifyCSS(minifyCSSOptions))
			.pipe(gulp.dest(paths.prod + 'css'));
	});

// 3. Compress JavaScript files and place them into production folder
	gulp.task('compress-js', function() {
        console.log("Running compressing JavaScript task...");
		return gulp.src(paths.scripts)
			.pipe(concat('all-scripts.js'))
			.pipe(gulp.dest(paths.prod + 'js'))
			.pipe(rename('all-scripts.min.js'))
			.pipe(uglify())
			.pipe(gulp.dest(paths.prod + 'js'));
	});

// 4. Copy images
	gulp.task('copy-static-resources', function() {
		// console.log("Copy images from:" + (paths.dev+paths.images));
        console.log("Copying static resources task...");
		gulp.src(paths.images)
			.pipe(imagemin({
				progressive: true,
				optimizationLevel: 6,
				svgoPlugins: [{ removeViewBox: false }],
            	use: [pngcrush({ reduce: true })]
			}))
			.pipe(gulp.dest(paths.prod + 'img'));

		gulp.src(paths.dev+paths.fonts)
			.pipe(gulp.dest(paths.prod + 'fonts'));
	});



// Watch files for fhanges
gulp.task('watch', function() {
    //gulp.watch(paths.scripts, ['create-documentation']);
    //gulp.watch(paths.scripts, ['compress-js']);
    console.log("Registering path to watch:" + paths.dev + paths.stylus);
    gulp.watch(paths.dev + paths.stylus, ['stylus','compress-css']);
});


// Default gulp task to run
gulp.task('default',['stylus', 'compress-css', 'compress-js', 'copy-static-resources', 'watch']);

Installing packages in dev mode

Now, in order for having our tasks running we need to install the other plugins for Gulp.js like: gulp-concat, gulp-rename, gulp-watch, etc; so, just run next command to install them all together:

# Set the gulp.js in dev mode
npm install --save-dev gulp

# Set other modules in dev mode
npm install --save-dev gulp-concat gulp-rename gulp-watch gulp-uglify gulp-stylus gulp-imagemin

Running tasks

Finally, let’s run a task for compiling all our .styl files into CSS and one task for copying all our static resources; the  images will be optimized for web in this task, btw.

Stylus is a CSS pre-processor like LESS or SASS/SCSS; much more elegant than having just CSS syntax in our projects. Stylus has a Python-like syntax; so, if you like Python you will love Stylus.
gulp <NAME_OF_TASK>

# Example to execute 'stylus' task
gulp stylus

# Example to run 'copy-static-resources' task
gulp copy-static-resources

If you want to run many tasks by default, you can just type in your command line:

# This will run the default task, which executes others.
gulp

BTW, a complete functional repository with Gulp.js tasks is available in this link: https://github.com/alex-arriaga/fcc-buap-taller-frontend.

Ok, that’s it for today; I hope you find this information useful, see you next time!

One comment on “Getting started with Gulp.js from scratch”

Leave a Reply

Your email address will not be published. Required fields are marked *