Gulp validate javascript before go live

With gulp we can validate our javascript files before it crashes. follow these steps to validate javascripts files using gulp-jsValidate.
first thing we need to install gulp, gulp-cli and gulp-jsValidate with gulp-debug.
then

var gulp = require('gulp'),
    jsValidate = require('gulp-jsvalidate'),
    debug = require('gulp-debug');

gulp.task('default', function () {
    return gulp.src('app.js')
        .pipe(debug())
        .pipe(jsValidate());
});

here we can pass a single file path or array of files in gulp.src.
for validating file on the fly we must implement it by gulp-watch.

Gulp XML to Json

To converting xml to json format we have a gulp-xml2json available. follow these step to convert xml to json.

    var gulp = require('gulp'),
        xml2json = require('gulp-xml2json'),
        rename = require('gulp-rename');

    gulp.task('sitemapjson', function () {
        gulp.src('sitemap.xml')
            .pipe(xml2json())
            .pipe(rename({extname: '.json'}))
            .pipe(gulp.dest('./'));
    });

A good scenario is to download the sitemap.xml file from online sitemap generator then convert the xml file to json with gulp-xml2json then integrate it with gulp-psi to get a page speed of all available pages of your website.

Gulp PSI a command line tool for fetching google page speed

Gulp PSI CLI Tool

PSI module is available for getting page speed. to set it up with gulp follow these steps.

First install gulp-cli and psi via npm

const psi = require('psi');
var gulp = require('gulp'),
    site = "http://my-website.com";

gulp.task('desktop', function () {
   psi(site, {
            nokey: 'true',
            strategy: 'desktop',
        })
       .then(function (data) {
            console.log(site +" \tdesktop\t"+ data.ruleGroups.SPEED.score);
        });
});

gulp.task('Mobile', function () {
   psi(site, {
            nokey: 'true',
            strategy: 'mobile',
        })
       .then(function (data) {
            console.log(site +" \mobile\t"+ data.ruleGroups.SPEED.score);
        });
});

Gulp Minify images

To compress images for speeding up website we will use gulp here to minify images.
assuming that we already have node, gulp, gulp-cli in our system. we will use gulp-imagemin to compress images.

var gulp = require('gulp'),
    imagemin = require('gulp-imagemin'),
    DIR = "./build/";

Following is the gulp task for minify images.

gulp.task('minImages', function() {
    return gulp.src(['./images/*.jpg', './images/*.png'])
    .pipe(imagemin({ progressive: true }))
    .pipe(gulp.dest(DIR+'/images/'));
});

by running above command all the jpg and png files inside the images folder will compress and will be created inside build/images/ folder.

Gulp Upload file to S3

For uploading file on S3 we use gulp-s3 Module. To use this module we must have gulp and gulp-cli already installed.
First we need to create a aws.json file for credentials.
The format for file is like

{
  "key": "AKIAI3Z7CUAFHG53DMJA",
  "secret": "acYxWRu5RRa6CwzQuhdXEfTpbQA+1XQJ7Z1bGTCx",
  "bucket": "dev.example.com",
  "region": "eu-west-1"
}

Now we first need to install gulp-s3 using gulp i –save gulp-s3 Command.
Once module is installed we will create a task for it.

Read more

Gulp Minify & Concat Javascript

To optimize the page speed we must do javascript minification and concat multiple javascript file to single file. Suppose we have a manifest.json file which has two nodes one for the libraries javascript files name array and second for all custom javascript file name array.
We have a const for build folder where all minified fill will save.

var gulp = require('gulp'),
    concat = require("gulp-concat"),
    eslint = require('gulp-eslint'),
    beautify = require('gulp-beautify'),
    uglify = require('gulp-uglify'),
    removeEmptyLines = require('gulp-remove-empty-lines'),
    fs = require('fs'),
    DIR = 'build/',
    ManFile = "manifest.json";

First we need all these packages for javascript minify and concat. Below is the task for creating two different version of js file one is debug and another is min file.

Read more

Gulp Inject css and js file in html page

Once we are done with javascript/css minify we need to update our html page to link to new build assets. There are some gulp tools available for that. Here we will also update the version for each assets after each deployment

var gulp = require('gulp'),
    inject = require('gulp-inject'),
    time = (new Date()).getTime();

var transform = function (filepath) {
		arguments[0] = filepath + '?v=' + time;
	return inject.transform.apply(inject.transform, arguments);
}

Below is the gulp task to inject css and js files

gulp.task("create-live-index",function(){
	var	target = gulp.src('./src/index.html'),
		cssfile = `${__dirname}/build/css/style.min.css`,
		jsfile = `${__dirname}/build/static.min.js`,
		libjsfile = `${__dirname}/build/library.js`,
		filesources = [cssfile,libjsfile,jsfile];
	
  	return target.pipe(inject(gulp.src(filesources,{read: false}),{
  			addRootSlash:false,
			transform: transform}))
    	.pipe(gulp.dest('./'));
});

This task will inject style.min.css in your html page. and library & static.min.js file in javascript section.

You also need to specify these tags into html page to inject css and js.
Place this tag where-ever you want to inject your css (replace # with <)
#!– inject:css –>
#!– endinject –>

For js use below tag
#!– inject:js –>
#!– endinject –>

Gulp Minify HTML

Gulp Minify HTML

To Minify html files via gulp first install gulp & gulp-htmlmin module with following command

npm i gulp --save
npm i gulp-htmlmin --save

Now in your gulp file require modules

var gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin');

Create following task for minify html

gulp.task('minifyHTML', function(){
    return gulp.src('index.html')
    .pipe(htmlmin({collapseWhitespace: true, minifyJS:true,removeComments:true}))
    .pipe(gulp.dest('./'));
});

you can pass following options to minify html.

Read more

Gulp Concat and Minify CSS

Gulp Concat and Minify CSS

First we need to create a manifest.json file which will have list of all css/js files in it. we create manifiest.json file to show different files on pages as per environment. Like in local/Dev we need to show all different css and for production we will contact and merge all css to show on page.

By using gulp we can automate this process like

var gulp = require('gulp'),
    concatCss = require('gulp-concat-css'),
    minifyCSS = require('gulp-minify-css');

gulp.task("copy-css", function(){
    var manifestFile = './manifest.json',
        json = JSON.parse(fs.readFileSync(manifestFile)),
        links = json.links;

    gulp.src(links)
        .pipe(concatCss("style.css"))
        .pipe(gulp.dest("build"));
    
    gulp.src(links)
        .pipe(concatCss("style.min.css"))
        .pipe(minifyCSS())
        .pipe(gulp.dest("build"));
});

First we need to installed required gulp modules using npm and then the about gulp task will read the manifest.json file anc create two version of css in build folder, One is .min and another is simple. which we will include in pages. here manifest.json template is like

{
    "links" : [
	"css/style.css"
    ]
}