Task Automation using Grunt Part-2

Pankaj Salunkhe

Pankaj Salunkhe

Technical Specialist at CG
Microsoft Certified Solution expert in SharePoint and O365 with 9+ years of experience.

write to admin@sharecareinspire.com for contribution
Pankaj Salunkhe

Latest posts by Pankaj Salunkhe (see all)

<<Part 1       >> Related Articles      Download Code

In previous part we have seen how grunt helps in automation of repetitive tasks during development and deployment phase.

Benefit of using Grunt is that it has huge ecosystem of plugins to perform various tasks, but at the same time it is little difficult to configure different plugins.

Let’s take discussion one step further and see few more scenarios

Tasks: Conversion, Minification and Watch

This article focuses on tasks Compilation, Validation, Minification and Compression. Lets have a look step by step. This sample is referred from github, you can also download code from there.

 

Step 1: Create folder Grunt-Demo using Node.js command prompt

Step 2: Open the folder in visual studio code by below command from Node.js command prompt.

Step 3: Create file package.json from visual studio code. Add the below code

{
  "name": "grunt-getting-started",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-typescript": "latest",
    "grunt-contrib-jshint": "latest",
    "grunt-contrib-uglify": "latest",
    "jshint-stylish": "latest",
    "grunt-contrib-less": "latest",
    "grunt-contrib-cssmin": "latest",
    "grunt-contrib-watch": "latest"
  }
}

Step 4: Create file Gruntfile.js from visual studio code.

This is important file in which all type of tasks are configured along with source and destination paths and files.

Also if you have a requirement of converting files to destination automatically whenever there is a change in the file, you can configure a task watch change in source file and execute configured task.

in this example we have configured following type of tasks.

Type of TaskSourceDestination
1. Less to CSSPreety.lessPreety.css
2. CSS to Minify CSSStyle.cssStyle.min.css
3. TypeScript to JavaScriptHello.tsHello.js
4. Uglify to Minify jsMagic.jsMagic.min.js
module.exports = function(grunt) {
  // ===========================================================================
  // CONFIGURE GRUNT ===========================================================
  // ===========================================================================
  grunt.initConfig({
    // get the configuration info from package.json ----------------------------
    // this way we can use things like name and version (pkg.name)
    pkg: grunt.file.readJSON('package.json'),
     // compile typescript to javascript----------------------------------------
     typescript: {
      build: {
        files: {
          'dist/js/Hello.js': 'src/js/Hello.ts'
        }
      }
    },
    // configure jshint to validate js files -----------------------------------
    jshint: {
      options: {
        reporter: require('jshint-stylish')
      },
      all: ['Grunfile.js', 'src/**/*.js']
    },
    // configure uglify to minify js files -------------------------------------
    uglify: {
      options: {
        banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
      },
      build: {
        files: {
          'dist/js/magic.min.js': 'src/js/magic.js'
        }
      }
    },
    // compile less stylesheets to css -----------------------------------------
    less: {
      build: {
        files: {
          'dist/css/pretty.css': 'src/css/pretty.less'
        }
      }
    },
    // configure cssmin to minify css files ------------------------------------
    cssmin: {
      options: {
        banner: '/*\n <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> \n*/\n'
      },
      build: {
        files: {
          'dist/css/style.min.css': 'src/css/style.css'
        }
      }
    },
    // configure watch to auto update ------------------------------------------
    watch: {
      stylesheets: {
        files: ['src/**/*.css', 'src/**/*.less'],
        tasks: ['less', 'cssmin']
      },
      scripts: {
        files: 'src/**/*.js',
        tasks: ['typescript','jshint', 'uglify']
      }
    }
  });
  // ===========================================================================
  // LOAD GRUNT PLUGINS ========================================================
  // ===========================================================================
  grunt.loadNpmTasks('grunt-typescript');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-watch');
  // ===========================================================================
  // CREATE TASKS ==============================================================
  // ===========================================================================
  grunt.registerTask('default', ['typescript','jshint', 'uglify', 'cssmin', 'less']);
};

Step 5: Create folder src/js and  src/css under Grunt-Demo

These folders will contain source files on which tasks such as compression and conversion needs to be performed.

Step 6:  Create magic.js file in src/js folder

$("p").on({
    mouseenter: function(){
        $(this).css("background-color", "lightgray");
    },
    mouseleave: function(){
        $(this).css("background-color", "lightblue");
    },
    click: function(){
        $(this).css("background-color", "yellow");
    }
});

 

Step 7:  Create file Hello.ts under src/js folder

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}
let greeter = new Greeter("world");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());
}
document.body.appendChild(button);

Step 8: Create file pretty.less under css folder

@red        : #CC594A;
@yellow     : #B8CC24;
@blue       : #8BC5FF;
@purple     : #6F3596;
body        {
    background:@red;
    color:@yellow;
}
button      {
    background:@blue;
}
div         {
    background:@purple;
}

 

Step 9: Create file style.css under css folder

body {
  background: #cc594a;
  color: #b8cc24;
}
button {
  background: #8bc5ff;
}
div {
  background: #6f3596;
}

Step 10: Run “npm install” command from node.js command prompt

This command will install dependent libraries and creates folder node-modules.

Step 11: Run “grunt default -v” command from node.js command prompt

This command generates the files under destination folder with respective tasks.

You will notice that files from source folder are converted and placed in destination folder

Type of TaskSourceDestination
1. Less to CSSPreety.lessPreety.css
2. CSS to Minify CSSStyle.cssStyle.min.css
3. TypeScript to JavaScriptHello.tsHello.js
4. Uglify to Minify jsMagic.jsMagic.min.js

Task watch to auto update is also configured so that whenever there is a change in source file automatically task will be executed and files gets converted to destination type.

Step 12: Following conversion took place

  • Less to CSS : converted pretty.less to pretty.css
body {
  background: #CC594A;
  color: #B8CC24;
}
button {
  background: #8BC5FF;
}
div {
  background: #6F3596;
}
  • CSS to Minified css : converted style.css to style.min.css
body{background:#cc594a;color:#b8cc24}button{background:#8bc5ff}div{background:#6f3596}
  • Typescript to JavaScript : converted Hello.ts to Hello.js
var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();
var greeter = new Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);

  • Uglify to Minify js : converted magic.js to magic.min.js
$("p").on({mouseenter:function(){$(this).css("background-color","lightgray")},mouseleave:function(){$(this).css("background-color","lightblue")},click:function(){$(this).css("background-color","yellow")}});

You can also take advantage of grunt by writing your own automated task, if already not available in market by other third-party Grunt tasks.

<<Part 1       >> Related Articles      Download Code


Check Articles From Categories      Health and Parenting      Inspiring Stories      Technology      Microsoft Azure      SharePoint O365

Leave a Reply

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