Wednesday, February 12, 2014

Automatic minification and concatenation of JavaScript files with Grunt


Automatic minification and concatenation of JavaScript files

I'll try to demonstrate how easy it is for you to set up your project with basic Grunt automatic deployment.
I'll show a very simple configuration for minification and concatenation of your javascript modules. To make this work you ought to have NodeJS already installed on your machine. I use version 0.10.18 and npm version 1.3.8. These versions are available at the time of writing this post.

Here you can download the code from github.

This post will be divided into 2 sections:
1. setup your local test project
2. setup grunt file

Setup your local test project

First step is to create a package.json file in your project's folder:

package.json:
 {  
  "name": "grunt-test",  
  "version": "0.0.1-1",  
  "private": false,  
  "scripts": {  
   "start": "app.js"  
  },  
  "dependencies": {  
   "grunt": "~0.4.2",  
   "grunt-contrib-concat": "~0.3.0",  
   "grunt-contrib-uglify": "~0.2.5"  
  },  
  "subdomain": "localhost",  
  "domains": [  
   "localhost"  
  ],  
  "engines": {  
   "node": "0.10.x"  
  }  
 }  
Now, using command line go to the folder where your package.json file is and use npm install command to install all your "dependencies" (node modules).
As soon as you finish downloading all of the dependencies, create our main app file - app.js.
This one is meant to be very simple in this tutorial, with only one node dependency ("connect") to enable you to see the results of minification and concatenation.

app.js:

 var connect = require('connect');  
 connect.createServer(  
  connect.static(__dirname)  
 ).listen(8080);  
Now in the same folder as package.json and app.js create our index.html.

index.html:

 <html>  
 <head>  
  <title>Grunt test</title>  
 </head>  
 <body>  
  <h2>Hello Grunt</h1>  
  <p>Press F12 and go to Console</p>  
 <!-- this is our minified and concat version of js -->  
 <script type="text/javascript" src="public/js_dist/app.js"></script> </body>  
 </html>  
The last step is the creation of your js files which you are going to minifi and merge. Create "public/js/" folder and "public/js_dist" folder.
Inside "public/js/" create "module_one.js" and "module_two.js".

module_one.js:
 (function () {  
  console.log('hello world - this is the first module');  
 })();  
module_two.js:
 (function () {  
  console.log('... and our second module');  
 })();  
Setup Grunt

Create Gruntfile.js in the root directory. This file is responsible for telling Grunt what to do when we run grunt commands.
 'use strict';  
 module.exports = function (grunt) {  
  /* The main configuration for your dev env. Put all your magic here */  
  grunt.initConfig({  
   pkg: grunt.file.readJSON('package.json'),  
   concat: {  
    options: {  
     separator: ";"  
    },  
    dist: {  
     src: ['public/js/*.js'],  
     dest: 'public/js_dest/app.js'  
    }  
   },  
   uglify: {  
    options: {  
     banner: "/* here you can put some comments about your app */"  
    },  
    dist: {  
     files: {  
      "public/js_dest/app.js": ['<%= concat.dist.dest %>']  
     }  
    }  
   }  
  });  
  /* tell Grunt what deps you want to load */  
  grunt.loadNpmTasks('grunt-contrib-uglify');  
  grunt.loadNpmTasks('grunt-contrib-concat');  
  /* register our "grunt build" task */  
  grunt.registerTask('build', ["concat", "uglify"]);  
 };  

Rememeber:- we use "initConfig" method to define actions we want Grunt to perform
- we use "loadNpmTasks" to load plugins
- we use "registerTask" to define grunt commands

Now, use grunt build command in your root directory. Voila! Our modules should be minified and concatenated.

Now, using command line go to your project folder where you should be able to run node app.js command. In your favorite browser go to http://localhost:8080 to see the page. In the dev tools console you should see the texts from the "console.log" in two modules.

Remember, that our modules should be independent of one another if you want to use this method alone to develop your application. You might get confused on the order modules are concatenated at some point. Very good idea is to use e.g. RequireJS to be sure when and where our modules are loaded.

For more blog posts go to http://ds-web-dev.com/blog.

This post has been inspired by HTML5DevConf " Continuous Delivery for JavaScript Applications" presentation.

Reference



4 comments:

  1. Your ideas on how to build an attractive website to grab customers to your business is excellent with the required functionalities. I hope your article was most read for the web related searchers in the internet. Keep updating your ideas, I am waiting for the article.
    Regards:
    web designing training in chennai |web design training in chennai

    ReplyDelete
  2. This is the reason marketing promotions campaigns so that you can useful investigate earlier than posting. It will be easier to put in writing more effective place like this. Smart Contract Development Process bangalore

    ReplyDelete