Grunt
In this tutorial we will learn to use Grunt cssmin plugin in our project to minify CSS file.
In the previous tutorial we learned how to minify JavaScript file using Grunt plugin Uglify. In this tutorial we will be minifying CSS file using cssmin plugin.
Let us assume that we have the following project structure. The name of the project is grunt-project.
Inside the css folder we have style1.css and style2.css files. These are the files that we are going to minify.
Content of style1.css
file.
/**
* from file 1
*/
p {
font-size: 16px;
}
Content of style2.css
file.
/**
* from file 2
*/
.container {
width: 100%;
}
.success {
background-color: lightgreen;
}
.error {
background-color: red;
}
We will be writing the following code in Gruntfile.js file.
module.exports = function(grunt) {
//project configurations
grunt.initConfig({
cssmin : {
target : {
src : ["css/style1.css", "css/style2.css"],
dest : "dist/style.min.css"
}
}
});
//load cssmin plugin
grunt.loadNpmTasks('grunt-contrib-cssmin');
//create default task
grunt.registerTask("default", ["cssmin"]);
};
So, let's get started.
Run the following command in the terminal to install cssmin plugin in the project.
$ npm install grunt-contrib-cssmin --save-dev
Output
YUSUF-MacBook-Pro:grunt-project yusufshakeel$ npm install grunt-contrib-cssmin --save-dev
grunt-project@1.0.0 /Users/yusufshakeel/Documents/GitHub/grunt-project
└─┬ grunt-contrib-cssmin@2.0.0
└── clean-css@4.0.9
YUSUF-MacBook-Pro:grunt-project yusufshakeel$
Open Gruntfile.js file and type the following.
module.exports = function(grunt) {
}
In the above code we are creating a function that is used in every Grunt file and its plugins.
Now, inside the function that we created above write the following code.
grunt.initConfig({
});
So, we are passing an object to initConfig
method of Grunt. All our configuration for grunt will go inside this object.
Now, inside the object set the cssmin
property to the following value.
cssmin : {
target : {
src : ["css/style1.css", "css/style2.css"],
dest : "dist/style.min.css"
}
}
In the above code we are adding the target property. In this we are saying that our source src files are style1.css and style2.css inside the css folder. And we want the minified file to have a name style.min.css and we want it inside the dist folder.
To load the cssmin plugin write the following code.
grunt.loadNpmTasks('grunt-contrib-cssmin');
Now, at the end we will create a default task for the Grunt by typing the following code.
grunt.registerTask("default", ["cssmin"]);
Finally to run the task type the grunt
command in the terminal and it will minify the CSS files using cssmin.
YUSUF-MacBook-Pro:grunt-project yusufshakeel$ grunt
Running "cssmin:target" (cssmin) task
>> 1 file created. 178 B → 101 B
Done.
YUSUF-MacBook-Pro:grunt-project yusufshakeel$
After running the above command we will have the style.min.css
file inside the dist folder.
That's all for this tutorial. Have fun coding.
ADVERTISEMENT