TECHY360
Everything You Need To Know About Tech

What is Grunt? How to use it and its Cheatsheet

123

A Grunt is basically an automation tool used in programming. Basically if you are a developer then you will know that the development of any project consumes a lot of time and you need to perform some repetitive task Eg: Conversion of sass to CSS so this is very annoying task as you have to do it again and again and it will increase the development time so you can use grunt and automate these types of tasks and there is so much more you can do with Grunt. At the end of this tutorial, you will know everything about GRUNT

GRUNT Cheatsheet

Installing globally: npm install -g grunt-cli

grunt

Executes the Gruntfile.js located in the current directory. Specifically, the default task(s).

grunt-init

Grunt-init is a scaffolding tool used to automate project creation. It will build an entire directory structure based on the current environment and the answers to a few questions. The exact files and contents created depend on the template chosen along with the answers to the questions asked.

Examples:

grunt-init-gruntfile: Create a basic Gruntfile. grunt-init-jquery: Create a jQuery plugin, including QUnit unit tests. grunt-init-commonjs: Create a commonjs module, including Nodeunit unit tests.

Example in 5 Steps:

Step 1: package.json that contains:

{  
“name”: “my-project-name”, 
“version”: “0.1.0”,  
“devDependencies”: {    
       “grunt”: “~0.4.1”,   
       “grunt-contrib-jshint”: “~0.6.3”,v    
       “grunt-contrib-nodeunit”: “~0.2.0”,    
       “grunt-contrib-uglify”: “~0.2.2”  
  }
}

Step 2: Create a Gruntfile.js that contains:

module.exports = function(grunt) { 
 // Project configuration.  
 grunt.initConfig({    
     pkg: grunt.file.readJSON(‘package.json’),    
     uglify: {      
     options: {        
             banner: ‘/*! <%= pkg.name %> <%= grunt.template. today(“yyyy-mm-dd”) %> */\n’      
     },      
     build: {        
           src: ‘src/<%= pkg.name %>.js’,        
           dest: ‘build/<%= pkg.name %>.min.js’      
     }    
   }  
 });  // Load the plugin that provides the “uglify” task.  
 grunt.loadNpmTasks(‘grunt-contrib-uglify’);  // Default task(s).  
 grunt.registerTask(‘default’, [‘uglify’]);
} 

Step 3: Run “sudo npm install”

Step 4: Create a simple JavaScript file in a folder called “src” and name it “simple example. js”

Step 5: Run “grunt”.

Notice it’ll minify your JavaScript file in the build directory. Step 1: package.json that contains:

Why use Grunt?

The Grunt ecosystem is huge and it’s growing every day. With literally hundreds of plugins to choose from, you can use Grunt to automate just about anything with a minimum of effort. If someone hasn’t already built what you need, authoring and publishing your own Grunt plugin to npm is a breeze.

  • Grunt can perform repetitive tasks very easily, such as compilation, unit testing, minifying files, running tests, etc.
  • Grunt includes built-in tasks that extend the functionality of your plugins and scripts.
  • The ecosystem of Grunt is huge; you can automate anything with very less effort.
Advantages & Disadvantages of Grunt
Advantages & Disadvantages of Grunt

Advantages

  • Using Grunt, you can perform minification, compilation, and testing of files easily.
  • Grunt unifies the workflows of web developers.
  • It speeds up the development workflow and enhances the performance of projects.

Disadvantages

  • Whenever npm packages are updated, you need to wait until the author of the Grunt updates it.
  • Grunt includes a large number of configuration parameters for individual plugins. Usually, Grunt configuration files are longer in length.

How to use Grunt

Let’s first breakdown a typical workflow to get a big picture:

  1. Install Node.js and Grunt.
  2. Create package.json and list dependencies (Grunt and plugins).
  3. Install NPM modules.
  4. Create Gruntfile.js.
  5. Configure tasks you need to run.
  6. Run those tasks in the command line while you work.

Setting up the environment

Having Node.js is a prerequisite. If you don’t know how to install node js follow this tutorial.

How to install node.js npm manager on windows and mac?

First, you need to install Grunt for the command line as a global module, after which you have grunt command available globally.

sudo npm install -g grunt-cli

-g: It is used to make the node package manager available globally.

In this tutorial we will build the project: use Sass to write the stylesheets.
If you don’t know about Sass read this article on Sass.

What is Sass And how to use it?

CoffeeScript for scripts, introduce asset pipeline (concatenation and minification) and live to reload of the page whenever there is a change in source files. Whenever you save any changes to files it will auto restart the server so you don’t need to perform that repetitive task again.

What is CoffeeScript and how to use it?

The initial project folder structure should look like this:

project
├── Gruntfile.js
├── index.html
├── package.json
├── scripts
│   ├── hello.coffee
│   └── main.js
└── styles
    └── main.scss
mkdir -p project1/{scripts,styles} 
cd project1
touch Gruntfile.js index.html package.json scripts/coffee.cofee scripts/main.js styles/main.scss

First, we need Grunt for the project (which is separate from the grunt-cli used to run grunt command). We install it via npm. So we need to fill package.json and list grunt as a dependency and some plugins which will perform the tasks:

Related Posts
1 of 7
{
  "devDependencies": {
    "grunt": "^0.4.5",                    // Core Grunt module
    "grunt-contrib-concat": "^0.5.0",     // Javascript concatenation
    "grunt-contrib-cssmin": "~0.10.0",    // CSS minification
    "grunt-contrib-sass": "^0.7.3",       // Sass processing
    "grunt-contrib-uglify": "^0.5.1",     // Javascript minification
    "grunt-contrib-watch": "^0.6.1",      // Watch for change in file and reload
    "grunt-contrib-coffee": "~0.12.0"     // CoffeeScript processing
  }
}

Now we run local installation of packages which should put node_modulesdirectory in the project folder along with the listed modules.

npm install

Note: you can run npm install grunt-some-plugin --save-dev to install the plugin and automatically save it in package.json as a dependency.

Grunt configuration

Next step is to create configurations in your Gruntfile.js file and define how the command grunt will behave. Every Gruntfile has four distinct regions:

  • The “wrapper” function,
  • Project and task configuration,
  • Loading Grunt plugins and tasks,
  • Custom tasks and aliases.

At the start we need to wrap everything with grunt global object:

module.exports = function(grunt) {
};

Inside the above function we define our configuration for various tasks, load them and create custom tasks like this:

grunt.initConfig({
  task: { }
});

grunt.registerTask(taskName, [optional description, ] taskFunction);

grunt.loadNpmTasks('yourplugin');

Note that since grunt.initConfig() is a regular function, you can use any valid Javascript to make configuration programmatic.

First task – Sass processing

First, write some style rules in your main.scss. After that, we can configure Grunt to process the Sass file with one command. To process the files we need grunt-contrib-sass plugin which should be already installed with npm in the project folder.

We first need to configure the task itself inside grunt.initConfig() function:

sass: {
  dev: {    // indicates that it will be used only during development
    files: {
      // destination     // source file
      'styles/main.css': 'styles/main.scss'
    }
  }
}

As you can see we name the task we wish to configure, then we define options, in this case which file to convert. First we define destination and name of the new processed file, then the source file.

You can add comma and define more files following the same format, use an array to hold several sources, or you can use globals and format input like this: styles/*.scss or **/*.scss. We can even make variable which will hold the values and use them instead for better programming practice.

Next we need to load the task after the grunt.initConfig() function:

grunt.loadNpmTasks('grunt-contrib-sass');

Now we are ready to go. Fire up your terminal and run the command to convert the file(s) and there should be a regular CSS file waiting for you.

grunt sass

CoffeeScript processing

Very similar to how we used the Sass plugin. Inside the grunt.initConfig()function add configuration for the coffee task. Then mark the task to load and run in the command line.

coffee: {
  compile: {
   files: {
    'scripts/hello.js': 'scripts/hello.coffee'
   }
 }
}
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt coffee

Asset compilation

Next we want our styles and scripts to be concatenated and minified (so the server needs to make fewer requests and load the page faster). Again, we configure some tasks and load them. First we define tasks inside grunt.initConfig() function:

cssmin: {
build: {
  src: 'styles/main.css',
  dest: 'styles/main.min.css'
}
},
concat: {
  options: {
    separator: '\n/*next file*/\n\n'  //this will be put between conc. files
  },
  dist: {
    src: ['scripts/hello.js', 'scripts/main.js'],
    dest: 'scripts/built.js'
  }
},

uglify: {
  build: {
    files: {
      'scripts/built.min.js': ['scripts/built.js']
    }
  }
}

cssmin is responsible for minification of CSS files, concat for Javascript concatenation and uglify for Javascript minification.

grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-concat');

At this point we can run individual tasks like grunt concatgrunt uglify etc. But since we would always run them one after another, it would be useful to define a custom task that will run a set of commands: one for sass+cssmin, and the another for coffee+concat+uglify.

Custom tasks

We can create our own custom tasks that run when we call them from command line. It is done by creating aliases before or after loadNpmTasks(). We can create what task(s) to run by default when we just run grunt, or custom tasks with custom name (alias) command where we put various tasks we wish to run in an array, in order in which we want them executed.

// grunt.registerTask(taskName, [optional description, ] taskFunction)
grunt.registerTask('default', ['sass']);
grunt.registerTask('css', ['sass', 'cssmin']);
grunt.registerTask('js', ['coffee', 'concat', 'uglify']);
grunt
grunt css
grunt js

As we use Javascript, we can create custom functions and programmatically define what the tasks will do. You can check out the official documentation for more information on how to do this. Some of the things you can do this way include:

  • Tasks can be run inside other tasks
  • Tasks can be asynchronous
  • Tasks can access their own name and arguments.
  • Tasks can fail if any errors were logged, or continued if used --force flag
  • Tasks can fail if required configuration properties don’t exist.
  • Tasks can be dependent on the successful execution of other tasks.

Watching for file changes

After all the setup so far, it would be nice if those tasks would trigger automatically when we make a change to some files. Just for that kind of job there is a watch plugin.

Watch task runs a unique set of tasks when the file has been saved. We first need to configure watch, then run grunt watch which will continue to be ran until you cancel it as it listens for the save trigger.

Configure watch inside grunt.initConfig() as usual and load the task:

watch: {
  sass: {
    files: '**/*.scss', // ** any directory; * any file
    tasks: ['css']
  },
  coffee: {
    files: 'scripts/*.coffee',
    tasks: ['coffee']
  },
  concat: {
    files: ['scripts/hello.js','scripts/main.js'],
    tasks: ['concat']
  },
  uglify: {
    files: 'scripts/built.js',
    tasks: ['uglify']
  }
}
grunt.loadNpmTasks('grunt-contrib-watch');

As you can see we can segregate tasks in subtasks that are called only when we need them. From the example above, we can call grunt watch:sass and it will only evaluate files that end in .scss anywhere in the project folder and if we change them, css task will run. If we just run grunt watch all the subtasks will be evaluated concurrently.

You can now try making some change to main.scss file and upon save you should see automatic conversion to main.css. Same with CoffeeScript files.

Note the order at which tasks run, especially when you have multiple files. Be careful not to fall into infinite-loop trap when one change triggers another and another… Also note that grunt watch will run until you cancel the process, and with that in mind it should be put as the last task in the array.

Live reload

If you make a change to some source file, you can see that change reflected live in your browser because watch comes with live-reload option available. It is made possible by harnessing Node.js and it’s back-end power.

First make modification in the Gruntfile.js to the whole watch task inside grunt.initConfig():

watch: {
  sass: {
    files: '**/*.scss',
    tasks: ['css'],
    options: {
      livereload: 8889 // 8889 is the default port === true
    }
  },
  coffee: {
    files: 'scripts/*.coffee',
    tasks: ['coffee']
  },
  concat: {
    files: ['scripts/hello.js','scripts/main.js'],
    tasks: ['concat']
  },
  uglify: {
    files: 'scripts/built.js',
    tasks: ['uglify'],
    options: {
      livereload: true
    }
  },
  all: {
    files: ['**/*.html'],
    options: {
      livereload: true
    }
  }
},

Next add <script data-src="https://localhost:8889/livereload.js"></script> to the index.html (or other files as needed) before closing body tag.

Open the index.html file and run

grunt watch

As port 35729 is the default port for the live-reload, you can go to http://localhost:8889/ to see if it works. You should get a welcome json file.

Now try making some changes to the index.html and watch as the browser reflects that change. Same works for scss and coffee changes if everything is configured correctly.

You can learn more about live reloading and options on these repository homepages:

85%
Awesome
  • Learning
  • Coding
  • Ease

Get real time updates directly on you device, subscribe now.

Comments
Loading...

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More