Tuesday, 24 November, 2020

Grunt Like a Pro – A Whirlwind Introduction to the Grunt Task Runner

A quick, 5-minute, guided tour of Grunt, demonstrating Sass Compilation.

Grunt LogoYou know, it’s not just tennis players who Grunt to improve their game, software developers have been doing it for years too.

In all seriousness, Grunt is a command line automation tool, used to make repetitive development tasks easier. Similar tools include Gulp and Webpack. This post will fly through installation and set-up demonstrating Sass file compilation.

Installation

Grunt is built on NodeJS using JavaScript, so to use Grunt, you’ll need to install Node JS (https://nodejs.org/en/) first.

Once you’ve installed NodeJS, and by extension it’s JavaScript package manager the Node Package Manager (NPM), you use NPM to install Grunt by typing the following from the command line inside your project's working directory:

npm install -g grunt-cli
npm install grunt --save-dev

Side note: The two commands above are both necessary for Grunt to work. The-g installs NPM components globally on the system, without the-g they're installed locally within the folder where they're run. In this case -g grunt-cli is installing the grunt command to the system path, but grunt won't work unless you have the package installed locally too, which enables different projects to use different versions of grunt on a per project basis.

Configuration

Node and Grunt are configured by the package.js and gruntfile.js. files respectively.

Grunt is extended using plugins, which are actually Node modules and are installed using NPM.

Side note: NPM modules are recorded in the package.js  manifest file. If you commit package.js into source control other developers can run npm install to automatically install all the modules used by your project.

Grunt's configuration, how to use those plugins once installed, is specified within gruntfile.js. An example configuration file is shown below in this article.

To initialise your package.json file type npm init, which will create the package.json file. Just follow the instructions to create a file in your project's root folder.

A Demonstration using Sass

For our demonstration we’ll install the Sass and process a simple Sass file. This will requi installing both Ruby and Sass if you don’t already have them.

Let's start by taking a looking at our Sass file:

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

This is should seem fairly straightforward. It's simply setting some variables and using them in the body element.

On Windows, you're going to need to Install Ruby. Get it from http://www.ruby-lang.org/en/downloads/. Mac user should already have it installed.

Next install Sass using NPM. Type:

npm install -g sass

Then install the official Grunt Sass to CSS plugin use:

npm install grunt-contrib-sass --save-dev

Side Note: See https://github.com/gruntjs for the list of official plugins; including the Sass plugin being used here.

Finally, configure the grunt file - gruntfile.js - to use the Sass plugin.

    grunt.initConfig({

        /* SASS Plugin specific configuration options */
        sass: {
          dist: {
            options: {
              style: 'expanded'
            },
            files: {
                /* Look for style.scss and and concert to style.scss. */
                'generated.css': './style.scss',
            }
          }
        }
      });

      // LoadNPMTask prepares a plugin for use by grunt.
      grunt.loadNpmTasks('grunt-contrib-sass');

      /*====================================================================================*/
      // DEFAULT
      /*====================================================================================*/

      grunt.registerTask('build', ['sass']);

      // Default task
      grunt.registerTask('default', 'Default task - showing help', function() {

          grunt.log.writeln(
            'Some help: \n');

          grunt.log.writeln(
            'Type grunt build to compile style.sass.');
      });
  };

The code above is mostly Grunt boiler-plate. The content should be save to a file called gruntfile.js in the root of your project's directory. The comments in the source should explain what's going on.

The key points to take away:

  • Everything is written in JavaScript and wrapped inside grunt.initConfig().
  • The sass{} object is specific to the Sass plugin and its options.
  • LoadNPMTasks is required to make grunt aware of the installed module.
  • RegisterTaskdefines command line parameters for Grunt. Here, for example, grunt buildis being used to run the Sass plugin and compile the Sass file.

To run grunt and compile the Sass file type grunt build from the command line. This will compile and create a file called generated.css. With the contents of:

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

That's A Wrap

This was was a really quick and short introduction to Grunt. We covered installing Grunt, the Sass plugin, configuring Grunt to use the Sass plugin and running Grunt to compile some Sass script.

This was just a taste of what Grunt can do. Grunt has 70+ official plugins and countless unofficial ones. Now you can Grunt like a pro too.

Want to Say Thanks for This Article?

Why not buy me a coffee  at https://www.paypal.me/justaguycoding?