compressed js with nodejs & gruntjs
TRANSCRIPT
Nguyễn Ngọc Dũng
https://nndung179.wordpress.com Page 1
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:
4. At folder JSCompressed create files:
a. package.json
{ "name" : "menory", "title" : "test", "version" : "1.0.0", "devDependencies": { "grunt": "0.4.1", "grunt-contrib-concat": "0.1.3", "grunt-contrib-cssmin" : "0.6.1", "grunt-contrib-watch" : "0.5.3", "grunt-contrib-uglify" : "0.2.0" } }
5. Open cmd
a. + cd to JSCompressed folder
b. Execute: npm install
6. Configuration Gruntfile.js
a. Gruntfile.js
Nguyễn Ngọc Dũng
https://nndung179.wordpress.com Page 2
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']); };
b. Explaination Gruntfile.js
concat: { js: { src: [ 'lib/jquery.js', 'lib/bootstrap.min.js' ], dest: 'combined.js' } },
Nguyễn Ngọc Dũng
https://nndung179.wordpress.com Page 3
This block of codes means: you will copy all source code fron js files into
1 file call 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.