The article put forth is to know how Grunt helped us to develop our Javascript SDK for AppWarp. The AppWarp JS SDK is originally written in Typescript, which is then trans compiled into Javascript. Typescript is a strict superset of JavaScript.
Why we needed Grunt?
To Automate. As explained above our AppWarp SDK was written in TypeScript. The complete SDK was divided into several files, and every time we had to compile those files into Javascript, join & minify them. This entire process was tedious & painful. This is why we decided to automate the process. Here, Grunt helped us to achieve our goal of automation. We automated in such a way that whenever any change is made in source files, the whole process of compilation and minifying runs itself, allowing us to focus only on writing our code.
What is Grunt and how it works?
Grunt is a Javascript task runner and requires node.js. It already supports many plugins that can be used to define tasks. To use grunt, you need to have a file named gruntfile.js that should contain all the task’s information. gruntfile.js is written in Javascript. You can also create this file in coffeescript, for which the file has to be renamed as gruntfile.coffee.
AppWarp JS SDK uses following plugins.
- grunt-typescript
- grunt-contrib-watch
- grunt-contrib-connect
- grunt-open
- grunt-contrib-uglify
Setting Up Grunt and Grunt-Plugins
1. Install grunt command line interface with npm globally
npm install -g grunt-cli
2. Create a package.json file with
npm init
3. Once you have package.json, install grunt and grunt-plugins in devDevependencies
npm install grunt --save-dev
npm install grunt-contrib-watch --save-dev
npm install grunt-contrib-connect --save-dev
npm install grunt-open --save-dev
npm install grunt-contrib-uglify --save-dev
Creating gruntfile.js
gruntfile.js is required to run grunt. In this file, you have to load your plugins, define and register the tasks.
gruntfile.js is defined like a node.js module. An example for the same is given below.
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-typescript');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
typescript: {
lib: {
src: ['src/lib/*.ts'],
dest: 'lib/appwarp.js',
options: {
module: 'amd',
target: 'es5',
declaration: true
}
}
}
});
grunt.registerTask('default', ['typescript']);
}
In the above file, we are defining a node.js module where we first load the plugin “grunt-typescript”, following that we defined typescript task, which takes all the .ts file and generated the appwarp.js file. Finally, we registered typescript as default task, therefore running grunt command in root directory of this project will automatically call the typescript task.
Alternative to grunt?
There is a popular alternative to grunt, called gulp. Although we haven’t tried it yet but like grunt even gulp looks very useful.
If you have any question or need further assistance, please feel free to write to us at Forum.
Leave A Reply