Working with grunt

Grunt is a very powerful resource managed by npm which is a node.js’s package manger. It helps to organized your working files and folders. It can perform an activity such as compiling sass, optimizing images, optimizing html pages, optimized js, css files, removing comments, compile coffee script, etc..

Working with Grunt

Before working with Grunt make sure you have node.js installed in your computer. Refer to my previous post Install NodeJS to see how to install nodejs.

Setting up Grunt

A typical setup for Grunt will require two main files in the root of your project. package.json and Gruntfile.js. So lets create these two files in the root of our directory.
1) Create file package.json
2) Create file Gruntfile.js

In package.json, there will be a a list of metadata of npm modules. Where as Gruntfile.js is used to define task and load grunt plugins. The name of the file is Gruntfile.js. It can also be named as Gruntfile.coffee

Next step is to open your command line. Click on start and search for “command”. Navigate the command directory to your project directory. Then type:-npm install
This is download all the modules you have mentioned in your package.json and all the necessary files and folders. They are all needed to make the listed thing work.
It will also create a new folder called node_modules. You don’t have to do anything with this folder. If you are using version controller like git, you can ignore this folder while pushing.

The next file we have to create is Grunfile.js We need to add some plain code to start.
Create file Gruntfile.js and paste the below code inside the file.

Inside the project configuration function, we have the plugin uglify in our Gruntfile.js. “src” is your source file where you are working For eg: custom.js and dest is a destination of your files after being compile.
The use of uglify is to compressed your file, delete all the white spaces and comments.
Checkout the uglify documentation what it really does. Every time a new package is installed, it is updated to package.json file. This file is present in the root of Grunt folder.

The function grunt.loadNpmTasks specifies the task name. In our case we are using a uglify. After that we register our task in another function called grunt.registerTask. You have to mention every new task and mentioned it in this below two function.

We are in the final stage of getting started with Grunt. Now lets open the command line and navigate to your project directory and typegrunt
We have “default” in our project name so we will use “grunt” without postfix.