Sunday, January 10, 2016

How to minify the css by using grunt.

By this article I would like to tell how to minify the css by using Grunt. I am not going to tell how to install nodejs and npm. We need this for run Grunt in our computer. I have provided the link through which you can get the information about install nodejs and npm.

There are few steps by which you would know how to minify the css through using grunt.

1) Install nodejs and npm by This.

2) Install Grunt Cli(command line interface) by running the command
    npm install -g grunt-cli
  
  -g indicates global which means by any where you can run the 'grunt' command
 
By running the command 'grunt', The below screen-shot will ensure 'grunt command line interface' is installed.


3) Create your project folder eg: myproject.
 .
4) In created project folder, make the file'package.json' for install grunt and it's css minimizer module. The content for this file would be
 {  
   "name" : "myproject",  
   "title" : "minycss",  
   "version" : "1.0.0",  
   "devDependencies": {  
     "grunt": "0.4.1",  
     "grunt-contrib-cssmin" : "0.6.1",  
   }  
 }  

5) Now from your project folder, run the command 'npm install' to install these modules(grunt, grunt-contrib-cssmin).
Now there will be installed the mentioned modules into node_modules folder.

6) Now create the Gruntfile.js file in your project folder(myproject). The content of Gruntfile.js file would be
 module.exports = function(grunt) {  
      grunt.initConfig({  
           pkg: grunt.file.readJSON('package.json'),  
           cssmin: {  
                mincss: {  
                     // src: ['*'], Minify all css files into one   
                     src: ['layout.css', 'color.css'], // For minimize the selected files from source folder  
                     dest: 'styles.min.css' // After minimized css of two files into one   
                }  
           }  
      });  
      grunt.loadNpmTasks('grunt-contrib-cssmin'); // grunt module for minimize css  
      grunt.registerTask('default', ['cssmin:mincss']); // registering task mincss  
 };  


7) Now from your project folder, run the grunt task by command 'grunt mincss'

After run this command there will be created the file called 'styles.min.css' in your project.

In Gruntfile.js file, the task mincss we have registered is doing main work, it's basically what doing is gets the all css from files layout.css and colors.css, After that it does combine and minify the css in single file called styles.min.css.