Introduction to ‘Grunt’ and its Tutorial

Introduction to ‘Grunt’ and its Tutorial

 

What’s the purpose of a technology if it doesn’t take away the pain of putting in extra efforts, which can be eliminated by automating a specific process?! We’re glad to have adapted and worked upon such technologies, tools, framework, and others, for the betterment of the projects we pick. Grunt is one such compiler tool that we use for automating the frequent tasks, freeing our team from the mundanity of such repetitive tasks.

 

Do you too wish to explore more about Grunt and adapt it in order to unburden yourself/your team from a range of such repetitive tasks? Well, here we share a small introduction about Grunt and a basic tutorial to get you started with it.

 

What is Grunt?

Grunt is an ecosystem created to automate a host of frequent tasks like minification, compilation, unit testing, and linting. It is a compiler tool for the designers to automate the repetitive tasks and speed-up the project. The core purpose of Grunt is to fasten and transform the way, a website is developed today.

 

Necessity of Grunt

“Necessity is the mother of invention,” they say. It applies to the invention of Grunt too. Working on JavaScript, one was required to execute a similar type of tasks for multiple times. Despite of being an integral part of the process, these bunch of repetitive tasks was quite time-consuming and mundane for the developers/designers. They needed a more productive and time-saving alternative of performing these repetitive tasks, without eliminating them. Apparently, that could be done only by automating the implementation of these repetitive tasks. And that is how the invention of Grunt was done.

 

Grunt Tutorial for the Beginners

We have been seeking the help of Grunt ever since its launch. And so far, we have had saved our team from the wastage of time and the headache of mundane activity. Let us share a tutorial on getting started with Grunt, which will help you in fastening your process and saving your team’s time and energy!

 

  • You can install and manage grunt and grunt plugin with the help of npm. To do so, you first need to setup node.js

  • After installing node.js, you need to install the CLI globally by using the command mentioned as below:

$ npm install -g grunt-cli

 

  • Now you need to check whether the Grunt has been properly installed or not, by using the following command. You can also check the Grunt version from here
$ grunt --version

 

  • Now you need to create package.json and gruntfile.js file in your project directory

Creating the package.json File: 

{
  "name": "mail-template",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5"
  }
}

 

  • package.json files are used to know which type of modules should be installed.

  • Once configured, you can either run npm install or npm update to update currently installed modules.

Creating the GRUNTFILE.JS File:

Grunt is actually configured using the gruntfile.js, which contains another JSON object. This one drives grunt with configuration for each module and order in, which each task and configuration is required to execute.

module.exports = function(grunt){
   grunt.initConfig({
       pkg: grunt.file.readJSON('package.json')
   });
   grunt.registerTask('default', []);
};

 

The above example of grunt and package.json file gives a basic overview of Grunt. In order to use Grunt with multiple tasks, you’re required to define the respective packages in the package.json file and tasks in the grunt file. This has to be done in such a manner that the conversion of sass into css task can be done, along with the inclusion of the required packages in the PACKAGE.JSON file and task for it in the grunt file.

 

Grunt is capable of performing a host of other tasks too. Check the reference plugin link for the same here: https://gruntjs.com/plugins.
 

Let us share one more example on converting scss to css, minified css and js file. In order to make this conversion possible, we’re extending the package.json file as follows:

{
  "name": "my demo",
  "version": "0.0.1",
  "description": "Learning Grunt and Sass",
  "license": "MIT",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-sass": "latest",
    "grunt-postcss": "latest",
    "autoprefixer": "latest",
    "grunt-contrib-cssmin": "latest",
    "grunt-contrib-uglify": "latest",
    "grunt-contrib-watch": "latest"
  }
}

 

  • Now run the npm install for installing these packages

  • Now, add the npm task in Grunt file. Here, we’re starting with the addition of the task for converting scss to css

Creating CSS From Sass Source Files:

sass: { // Begin Sass Plugin
      dist: {
        options: {
          sourcemap: 'none'
        },
        files: [{
          expand: true,
          cwd: 'sass',
          src: ['**/*.scss'],
          dest: 'css',
          ext: '.css'
      }]
      }
    }

 

  • Now, you need to define the load task

 

grunt.loadNpmTasks('grunt-contrib-sass');

 

  • Now, we will add one more task for converting it into minify css file.

  • This conversion will require us to add the below task in the Grunt file

cssmin: { // Begin CSS Minify Plugin
      target: {
        files: [{
          expand: true,
          cwd: 'css',
          src: ['*.css', '!*.min.css'],
          dest: 'css',
          ext: '.min.css'
    }]
      }
    }

 

  • Now add the grunt.loadNpmTasks('grunt-contrib-cssmin'); load taks

  • Now we will add js task

uglify: { // Begin JS Uglify Plugin
      build: {
        src: ['src/*.js'],
        dest: 'js/script.min.js'
      }
    }

 

  • This will require the addition of the task like
grunt.loadNpmTasks('grunt-contrib-uglify');

 

Automation of Tasks:

This a task that runs automatically, every single time when the file is being saved by us. This process will continue to run until the terminal is being closed or it is being manually stopped.

  • We will now add the watch task as below:
watch: { // Compile everything into one task with Watch Plugin
      css: {
        files: '**/*.scss',
        tasks: ['sass', 'cssmin']
      },
      js: {
        files: '**/*.js',
        tasks: ['uglify']
      }
    }

 

  • The npm task is like grunt.loadNpmTasks('grunt-contrib-watch');

Our final grunt file looks as below. You can add multiple other tasks in the grunt file by following the same method.

// Load Grunt
module.exports = function (grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // Tasks
    sass: { // Begin Sass Plugin
      dist: {
        options: {
          sourcemap: 'none'
        },
        files: [{
          expand: true,
          cwd: 'sass',
          src: ['**/*.scss'],
          dest: 'css',
          ext: '.css'
      }]
      }
    },
    
    cssmin: { // Begin CSS Minify Plugin
      target: {
        files: [{
          expand: true,
          cwd: 'css',
          src: ['*.css', '!*.min.css'],
          dest: 'css',
          ext: '.min.css'
    }]
      }
    },
    uglify: { // Begin JS Uglify Plugin
      build: {
        src: ['src/*.js'],
        dest: 'js/script.min.js'
      }
    },
    watch: { // Compile everything into one task with Watch Plugin
      css: {
        files: '**/*.scss',
        tasks: ['sass', 'cssmin']
      },
      js: {
        files: '**/*.js',
        tasks: ['uglify']
      }
    }
  });
  // Load Grunt plugins
  grunt.loadNpmTasks('grunt-contrib-sass');
  // grunt.loadNpmTasks('grunt-postcss');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Register Grunt tasks
  grunt.registerTask('default', ['watch']);
};

 

We hope our little tutorial has come to your help in some way or the other. In case, you’ve some suggestions to make, we’re all ears. Also, feel free to share your feedback on the same; or even better - have some topics in your mind that you want us to share our knowledge about? Great! Write to us and we’ll come up with the same in our upcoming blogs!