Getting Started with Grunt:Task Runner

06 / Feb / 2014 by Sahil Chitkara 1 comments

I was working on one of my projects which involved multiple task execution on regular basis. Well, I think that many of us have faced similar issues on their projects which increases our work and making it more time-consuming and increased work. Working in a community where people are actively developing tools to automate tedious processes, you assumes to have some tools to automate and speed up this process too.

For such scenarios, we have Grunt, to the rescue. I loved the way it made my work flow so easy.

Grunt already has a lot of plugins for the task like compiling less CSS, command shell, minifying CSS etc., or you can also create our own Grunt plugin for tasks which are repetitive or used on daily basis.

Now we will understand grunt with the help of a plugin called “cssmin”, used to minify CSS files.

Lets start with the setting up of grunt

  1. Installing grunt-cli globally
    npm install -g grunt-cli
  2. In your project directory install grunt and grunt plugin command
    npm install grunt --save-dev 
    npm install grunt-contrib-mincss --save-dev 
     It will add grunt and grunt plugins in devDependencies in package.json.
  3. Gruntfile.js or Gruntfile.coffee
    Gruntfile must be there in project root directory after .json package.This file contains

    • The “wrapper” function
    • Project and task configuration
    • Loading Grunt plugins and tasks
    • Custom tasks
      Gruntfile must look like:
    • [js]
      module.exports=function(grunt){
      //here grunt code comes
      //project configuration
      grunt.initConfig({
      pkg: grunt.file.readJSON(‘package.json’),
      cssmin:{
      minify: {
      expand: true,
      cwd: ‘public/stylesheets/css/’,
      src: [‘*.css’, ‘!*.min.css’],
      dest: ‘public/stylesheets/mincss/’,
      ext: ‘.min.css’
      }
      }
      });
      //load grunt plugins and register tasks
      grunt.loadNpmTasks("grunt-contrib-cssmin");
      grunt.registerTask(‘default’, [‘cssmin’]);
      [/js]


Now its your turn to be the magician. Open your terminal, go to your project directory and write 

grunt cssmin

All your minified css will be generated in destination directory which you have mentioned in Gruntfile.js.

Hope it will make your work flow easier 🙂

FOUND THIS USEFUL? SHARE IT

comments (1 “Getting Started with Grunt:Task Runner”)

  1. Pingback: How to use Grunt in existing project | TO THE NEW Blog

Leave a Reply

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