Gulp & Gulp plugins

Install Gulp

Use the following command to install gulp :

  • npm install -g gulp
  • npm install –save-dev gulp
  • To test the installation use following command:
    • gulp -v
  • Gulp is the streaming build system. It is recommended to install it globally as it can be required on multiple projects.

Install Gulp Plugins

Use the following command to install gulp plugins:

  • npm install gulp-sass gulp-concat gulp-uglify gulp-jshint gulp-rename –save-dev
  • Above command will install gulp plugins listed in the command. Sass, Concat, Uglify, jsHint & rename will be installed.

Screen Shot 2016-07-10 at 12.24.32 AM


Gulpfile.js

This file is the main file which is referred by Gulp to configure the application. It is made up of three sections:

  1. Gulp core and Gulp plugins declaration
  2. Task definition
  3. Task application

 

Gulp core and Gulp plugins declaration

In this step you will declare gulp and various plugins which are needed for the application.

var gulp = require(‘gulp’);

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

Task definition

Here you’ll define the tasks required to output the deployment code.

gulp.task(‘sass’, function(){
return gulp.src(‘scss/*.scss’)
.pipe(sass())
.pipe(gulp.dest(‘dist/css’))
});

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

gulp.task(‘scripts’, function() {
return gulp.src(‘js/*.js’)
.pipe(concat(‘all.js’))
.pipe(gulp.dest(‘dist’))
.pipe(rename(‘all.min.js’))
.pipe(uglify())
.pipe(gulp.dest(‘dist/js’));
});

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

Task application

Now that we have declared and defined everything, it is time to put those tasks into use.

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

Running the application

Use the following command to run the application:

  • gulp
  • This command will do the following:
    • Lint the JS files under js folder, concatenate them and minify them in one all.min.js under dist/js folder.
    • Compile the SCSS files into corresponding css file and place them under dist/css folder.
    • Keep a watch on JS and SCSS files for any updates.
  • The destination paths and order of tasks is configurable and flexible as per user’s choice.

Screen Shot 2016-07-10 at 12.13.30 PM

Advertisements