How to Use GRUNT JS in Java Development

In this article we will discuss about Grunt JS technology including the pre-requisites. By end of this tutorial we will also learn writing a grunt file for java application. Before we go into details lets learn what is Grunt JS.


ADVERTISEMENT

 

What is Grunt JS:

Grunt js is one of the JavaScript build tool developed using NodeJs, using Grunt JS tool we can bundle all application JS files and CSS files into single JS File, CSS file which in turn reduces network bandwidth usage drastically and provides better performance. Developers also use this tool to run unit tests and integration tests via grunt custom tasks.

 

Pre-requisites:

As Grunt JS is developed using NodeJS, it requires NPM (Node Package Manager comes bundled with Node.js installables after v0.6.3 version) to execute its tasks. The version of NodeJS must be 0.8.0 or later. Grunt tasks are written similar to Gradle tasks where we can execute and set default task if no task is specified on execution time. If the installed NodeJS is lesser than 0.8.0 then we have to  update the NodeJS using below command:

npm update -g npm

The above command will update our NodeJS to latest version.

 

Embedding Grunt into Java Applications:

If we are using Maven as build for Java applications, then we can use Maven plugin to invoke grunt tasks. You can download more plugins at Grunt plugin location here

Here in this example we are using Maven to complete the tutorial.

pom.xml file changes:

Add below plugin in pom.xml file.

<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.16</version>
</plugin>

 

Installing NodeJS:

Download NodeJS installer from here according to your operating System. Install  the downloaded package (exe) on your development machine and after successful installation run below command to see the current installed nodeJS version.

npm –version

 

Installing Grunt

Grunt supports Command Line Interface (CLI) tool which is available via grunt-cli plugin. We can install grunt-cli in two ways:

To install grunt-cli Project level:

npm install grunt-cli

Install globally i.e at NodeJS level:

npm install –g grunt-cli

After the executing above command make sure the node modules/bin folder contains the grunt and grunt.cmd files, and grunt command is available to current shell/command prompt session.

Writing a grunt file for Java Applications

Grunt depends on two important files, package.json and GruntFile.js. NodeJS requires package.json file to execute and install packages. You can create package.json on your own or from project directory. You can execute the npm init command to create sample package.json file for your project.

For installing grunt js for your project we need to specify grunt-cli as a nodeJS dependency.

  • We can specify below in devDependencies property.
"grunt": "^1.0.1",
"grunt-cli": "^1.2.0"
  • Execute the npm install grunt –save-dev and npm install grunt-cli –save-dev in shell/command prompt to download and update package.json file.

Please find sample package.json file:

{
"name": "sample",
"version": "1.0.0",
"description": "sample project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"grunt": "^1.0.1",
"grunt-cli": "^1.2.0",
"grunt-contrib-jshint": "^1.1.0",
"grunt-contrib-uglify": "^2.0.0"
},
"Dependencies": {
}
}

Note: package.json file contains two types of dependencies: devDependencies and DependenciesdevDependencies contains dependencies only needed for developers like running tests, code coverage and Dependencies is required for executing tasks, packaging, etc.

Writing Grunt file

To create Grunt file you need either Gruntfile.js or Gruntfile.coffee in project directory. If you are using JavaScript for writing grunt tasks then we need to create Gruntfile.js and if you are using coffee script then we need to create Gruntfile.coffee file.

An empty Gruntfile.js contains below text:

module.exports = function (grunt) {
}

Though Grunt has many plugins for different tasks but commonly used tasks are minifications, concatenations, running tests, etc. You can also extend the grunt tasks provided by plugins. A Grunt file contains below details:

  • Wrapper function
  • Task/Project Configuration
  • Loading grunt plugins/tasks
  • Custom tasks

Loading grunt plugins:

We can load grunt plugin using loadNpmTasks function by specifying the plugin-name like below

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

We can also get list of available tasks by executing grunt –-help command.

grunt js help

Writing grunt tasks:

Grunt tasks relies on the configuration data defined in grunt.initConfig method. We can also read the package.json file which we used for NodeJS.

You can use below method to import the data into initConfig method.

grunt.file.readJSON('package.json')

We can also get the property defined in package.json using <%property-name%>.

 

Configuration properties available for grunt plugin

For configuration properties go to grunt plugin folder and in tasks folder you will find a javascript file. You will find the find the options variable in the javascript file.

Example: For uglify plugins below options are available for plugin.

var options = this.options({
banner: '',
footer: '',
compress: {
warnings: false
},
mangle: {},
beautify: false,
report: 'min',
expression: false,
maxLineLen: 32000,
ASCIIOnly: false,
screwIE8: true,
quoteStyle: 0
});

The above configurations needs to be entered in initConfig method. For example, below are the configurations for uglifying files from src directory to build folder.

 

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});

You can register the default tasks using

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

Where we can specify comma (,) separated tasks in “[]” brackets for dependencies.

Example GruntFile.js :

module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
grunt.registerTask('default', ['uglify']);
}

Executing Grunt task with Maven for Java applications:

We need to add the below configurations in pom.xml file. Example pom.xml file can be found below.

<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.16</version>
<executions>
<execution>
<id>install node and npm</id>
<phase>generate-resources</phase>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v0.10.18</nodeVersion>
<npmVersion>1.3.8</npmVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<phase>generate-resources</phase>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>grunt build</id>
<phase>generate-resources</phase>
<goals>
<goal>grunt</goal>
</goals>
<configuration>
<arguments>--verbose</arguments>
</configuration>
</execution>
</executions>
</plugin>

Maven plugin don’t need local installed version nodeJS, install-node-and-npm goal will automatically download the npm and npm goal will resolve all dependencies specified in package.json file and grunt goal will execute the default task specified in Grunt file.

 

Conclusion

Grunt JS is the JavaScript build tool similar to maven, Gradle which is used to build/validate JavaScript files. Using grunt plugins you can write your own tasks and using loadNpmTasks method you can load grunt plugins. Grunt can be integrated with tools like maven so that packaging will be much easier and we can build deployable files.

If you have any queries about Grunt technology use for java applications, please leave a comment below for author to respond with details.

Guest Author Bio

Aaron Jacobson is a web developer working at Technoligent a java development company. He has several years of experience in the field of web development. you can ask any questions using the comments section.

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply