Editor’s note: We found an interesting series of articlesLearn 30 New Technologies in 30 Days, ready for translation, one update a day, year-end gift package. Here’s day five.


GruntJS is a Javascript based command-line build tool that helps developers automate repetitive tasks. You can think of it as Make or Ant in JavaScript. It can do things like downsizing, compiling, unit testing, lint checking, and more. As more and more development moves to the client, tools to help developers work more efficiently become more useful. In this article, I’ll show you how I can use GruntJS to simplify JavaScript files. We will also use GruntJS’s Markdown plugin to convert Markdown documents to HTML5 documents. Let’s get started!

Why should developers care about GruntJS?

The main reason is that developers are often looking for ways to automate daily tasks, which helps minimize the chance of errors. It’s easy to make mistakes when we’re doing repetitive, boring tasks by hand.

GruntJS rely on

GruntJS requires NodeJS version 0.8.0 or higher. We will use the NPM package manager to install GruntJS and its plug-ins. The new version of NodeJS includes the NPM package manager by default. You can download the latest version of NodeJS from the website.

GruntJS start

Before we begin, we need to understand the three main components of Grunt:

1. GruntJS CLI

GruntJS provides the GruntJS command line tool. The command to install the GruntJS CLI is mentioned below. If you encounter error messages during installation, you may need sudo permissions to run this command.

npm install grunt-cli -g

The command above installs the grunt- CLI package globally, so that it can be called from any directory. GruntJS CLI does not include Grunt Task Runner. To use Grunt Task Runner, we need to install it as a development dependency for our application. The separation of Grunt and Grunt-CLI ensures that each team member uses the same version of Grunt Task Runner.

2. GruntJS Task Runner

The grunk command calls the Grunt Task Runner. We need to install it as a development dependency for the application. Let’s start with a directory where we can put our sample blog application.

mkdir blog
cd blog

As mentioned above, Grunt is to be installed as an application development dependency. So we need to create a package.json file that defines the application meta information. Run the NPM init command and answer some questions to create the package.json file

$NPM init name: (blog) version: (0.0.0) description: My Awesome Blog entry point: (index.js) test command: git repository: keywords: author: license: (BSD-2-Clause) About to write to /Users/shekhargulati/blog/package.json: {" name ":" blog ", "version" : "0.0.0", "description" : "My awesome blog", "main" : "index. Js", "scripts" : {" test ": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "BSD-2-Clause" } Is this ok? (yes) Shekhars-MacBook-Pro:blog shekhargulati$

Once this is done, the init command will create the package.json file for us. Since we don’t need the main, scripts, author, and license items, we can delete them. Now we have our simplest package.json file.

{"name": "blog", "version": "0.0.0", "description": "My awesome blog"}

To install Grunt locally, run the following command:

npm install grunt --save-dev

The above command installs the required dependencies and also updates package.json.

{" name ":" blog ", "version" : "0.0.0", "description" : "My awesome blog", "devDependencies" : {" grunt ":" ~ 0.4.1 "}}

3. Grunt Plugins

GruntJS has a good plug-in system that handles most of the tasks we need. Plugins for GruntJS can be installed using NPM. In this article, we’ll use two plug-ins — Grunt-contrib-uglify and Grunt-Markdown. The full list of plug-ins is here.

Gruntfile

Now it’s time to tell GruntJS what tasks to do. If we run the grunt command in the blog directory, we will see the following error message:

$ grunt
A valid Gruntfile could not be found. Please see the getting started guide for
more information on how to configure grunt: http://gruntjs.com/getting-started
Fatal error: Unable to find Gruntfile.

To use Grunt, we need to create a file called gruntfile.js. The Gruntfile specifies the tasks that the grunt needs to perform. This file contains the build script.

Create a new file in the blog directory called gruntfile.js and add the following code:

module.exports = function(grunt){

};

This is the template we need to start using Gruntfile.

Then we need to configure the tasks that Grunt needs to perform. We call Grunt’s initConfig function and pass the configuration object to it. Currently, the configuration object is blank.

module.exports = function(grunt){
    grunt.initConfig({

    })  
};

streamline

The first task we’ll perform is to simplify the JavaScript files in our application. Create a JS folder in the blog directory, and create a new file called app.js.

$ mkdir js
$ cd js
$ touch app.js

Open app.js in a text editor and add the following to it. The app.js file has two simple methods, hello and bye.

function hello(name){
    return "Hello, " + name;
}
function bye(name){
    return "Bye, " + name;
}

Now let’s add the uglify task to the Grunt configuration object.

module.exports = function(grunt) {


  grunt.initConfig({
    uglify: {
      build: {
        src: ['js/app.js'],
        dest: 'js/app.min.js'
      }
    }

  });

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

  grunt.registerTask('default', ['uglify']);
};

The above code does this:

  1. We configureduglifyTask, which specifies the source and target files.
  2. And then we load itgrunt-contrib-uglifyThe plug-in. In the rungruntBefore the command, make sure the plug-in is installed. All Grunt plugins are availablenpmThe installation.
  3. Finally, we registered the uglify task as our default task. When we do not specify a task name and run directlygruntCommand, Grunt will invoke the default task.

If we run the grunt command, we will encounter the following message:

>> Local Npm module "grunt-contrib-uglify" not found. Is it installed?
Warning: Task "uglify" not found. Use --force to continue.

Aborted due to warnings.

Run the following command to install the grunt-contrib-uglify plug-in.

npm install grunt-contrib-uglify --save-dev

Then run the grunt command again, and this time we’ll see success.

$ grunt
Running "uglify:build" (uglify) task
File "js/app.min.js" created.

Done, without errors.

It successfully created the app.min.js file. As shown in app.min.js, all whitespaces are removed, the function parameters are refactored to a single letter, and the entire file is compressed into a single line.

function hello(a){return"Hello, "+a}function bye(a){return"Bye, "+a}

Today is day 4 of my Learn 30 New Technologies in 30 Days challenge. I’ve been enjoying it so far and getting a great response from the developers around me. A list of the entire series is here.


Day 5: GruntJS–Let Someone Else Do My Tedious Repetitive Tasks