Compressed JS with NodeJS & GruntJS

This tutorial will show you how to use grunt to compress js files from your project.

1. Install node js

2. Install Grunt CLI globally

npm install -g grunt-cli

3. For example, I have this structure of web:

1
4. At folder JSCompressed create files: package.json

{
 "name" : "menory",
 "title" : "test",
 "version" : "1.0.0",
 "devDependencies": {
 "grunt": "0.4.1",
 "grunt-contrib-concat": "0.1.3",
 "grunt-contrib-uglify" : "0.2.0"
 }
}

5. Open cmd

+ cd to JSCompressed folder

+ Execute:

npm install

6. Configuration Gruntfile.js
6.1. Gruntfile.js

module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        concat: {
            js: {
                src: [
                    'lib/jquery.js',
                    'lib/bootstrap.min.js'
                ],
                dest: 'combined.js'
            }
        },
        uglify: {
            js: {
                files: {
                    'combined.js': ['combined.js']
                }
            }
        },
    });
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.registerTask('default', ['concat:js', 'uglify:js']);
};

6.2. Explanation Gruntfile.js

concat: {
            js: {
                src: [
                    'lib/jquery.js',
                    'lib/bootstrap.min.js'
                ],
                dest: 'combined.js'
            }
        },

This block of codes means: you will copy all source code from js files into 1 file calls combined.js (A)

Note: at src attribute, you must place js files with the order of dependency.

uglify: {
            js: {
                files: {
                    'combined.js': ['combined.js']
                }
            }
        },

This block of codes means: from combined.js (A), you will compress you js here.

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

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

Load all module you have installed at step 5

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

This block of codes is very important, It means that after you do all configurations. You will register as task for Grunt to execute all tasks you have config above.

7. Result

The result of this procress will be a file with jquery & bootstrap in one file under compressed format.

8. Resource

https://github.com/nndung179/Compressed-JS-with-NodeJS-GruntJS

Leave a comment