Grunt your way to automation

The Gruntfile

In this file, a lot of the fun is defined. This is where you really need to not be afraid of not only breaking your site but your local environment. You will make a mistake or two but the key is to learn from it. The file begins with one simple line.

module.exports = function( grunt ) {

and ends with:

}; // end of module.exports

In order to configure our tasks we use the grunt.initConfig function and pass it our object with all the tasks. This is one way of doing this. Much like many things in life there is more than one way of achieving the same thing.

For example, if we wanted to take all the files in our project and make a zip file we would use the grunt-contrib-compress plugin and create a task in our Gruntfile. Looking at the documentation for the plugin we can use something like so:

module.exports = function( grunt ) {

	// Project configuration. This is where we define our
	// tasks and configure our task options. Notice that we
	// are passing a JavaScript object to the initConfig
	// function with our configuration.
	grunt.initConfig( {
		// We name our process and pass it some options
		compress: {
			main: {
				options: {
					// what our final zipped file will be named
					// do not forget the .zip part
					archive: 'package.zip'
				},
				// Where we define what files we want to compress
				// as well as what will not be included
				files: [ {
					src: [
						"**",
						"!**.{zip,svn,git}**",
						"!**/node_modules/**",
						"!**/bower_components/**",
						"!**/scss/**"
					]
				} ]
			}
		}
	} );

	// we load our plugin
	grunt.loadNpmTasks('grunt-contrib-compress');

	// we register our new task and map it to our newly created process
	grunt.registerTask( "zip", "compress" );
};

I am providing some inline documentation so you get an idea of what is happening. The file itself contains a few things.

  • Wrapper function
  • Task configurations
  • Loads grunt plugins and tasks
  • Custom tasks

The wrapper function is the module.exports function and the rest is our plugin and configuration. There is no custom task but you can create your own within the file to suit your project’s needs. Using Grunt plugins¬†can greatly reduce the time you spend on repetitive tasks like minifying CSS, JavaScript files or even copying all your theme’s PHP files into a dist¬†folder to prepare for compression and distribution which does go to show that automation can be a good thing.