The first thing that we want Grunt to be able to do is minify our files. Yes, we already have minifier installed, but remember that we want to use Grunt so that we can automatically execute a bunch of tasks (such as minification) in one go. To do so, we will need to install the grunt-contrib-cssmin package (a Grunt package that performs minification and concatenation. Visit https://github.com/gruntjs/grunt-contrib-cssmin for more information.):
npm install grunt-contrib-cssmin --save-dev
Once installed, inspect package.json. Observe how it has been modified to include the newly installed package as a development dependency:
{ "name": "MyPhoto", "version": "0.1.0", "devDependencies": { "grunt": "^0.4.5", "grunt-contrib-cssmin": "^0.14.0" } }
We must tell Grunt about the plugin. To do so, insert the following line inside the function definition within our Gruntfile.js:
grunt.loadNpmTasks("grunt-contrib-cssmin");
Our Gruntfile.js should now look as follows:
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON("package.json") }); grunt.loadNpmTasks("grunt-contrib-cssmin"); };
As such, we still cannot do much. The preceding code makes Grunt aware of the grunt-contrib-cssmin package (that is, it tells Grunt to load it). In order to be able to use the package to minify our files, we need to create a Grunt task. We need to call this task cssmin:
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), "cssmin": { "target": { "files": {
"dist/styles/myphoto.min.css": [
"styles/*.css",
"!styles/myphoto-hcm.css"
]
} } } }); grunt.loadNpmTasks("grunt-contrib-cssmin"); };
Whoa! That's a lot of code at once. What just happened here? Well, we registered a new task called cssmin. We then specified the target, that is, the input files that Grunt should use for this task. Specifically, we wrote this:
"src/styles/myphoto.min.css": ["src/styles/*.css"]
The name property here is being interpreted as denoting the output, while the value property represents the input. Therefore, in essence, we are saying something along the lines of "In order to produce myphoto.min.css, use the files a11yhcm.css, alert.css, carousel.css, and myphoto.css".
Go ahead and run the Grunt task by typing as follows:
grunt cssmin
Upon completion, you should see output along the lines of the following:
The first line indicates that a new output file (myphoto.min.css) has been created and that it is 3.25 kB in size (down from the original 4.99 kB). The second line is self-explanatory, that is, the task executed successfully without any errors.
Now that you know how to use grunt-contrib-cssmin, go ahead and take a look at the documentation for some nice extras!