Automate preparing your files for production using Grunt

You know you can use Grunt to automate some of the steps you already do when prepapring your code for production, but how do you actually go about it?

First, let's install Grunt

Fire up a console, navigate to the root of your project and then run:

$ npm install --save-dev grunt 

Then, create a file named Gruntfile.js in the root of your project:

module.exports = function(grunt) {
  // Project configuration - we have none yet!
  grunt.initConfig({
  });

  // Default task(s) - empty for now, no task configured yet
  grunt.registerTask('default', []);
}

To check that everything works, run the following command from the root of your project:

$ grunt
Done.

Configure the folder structure

What is your current file structure? Let's assume you just have some folders for your css, js and images:

app/
   - js/
     - index.js
   - css/
   - images/

Since you want to change the content of the js files for production, but also keep the original version intact, it helps to split the code into two subfolder: src for the original source files and dist for the ones that will be uploaded in the end to the server.

So go ahead and change your folder struture to something like this:

app/
  - src/
       - js/
         - index.js
       - css/
       - images/
  - dist/
       # Leave this empty for now, files will be put here by grunt

Start setting up gulp plugins

There a lot of Grunt plugins you can use, from minfying your javascript and css code, to compressing your images.

For a simple example of a task, head over to How to remove console.logs with Grunt.