Grunt Experienced Freshers Interview Questions Answers

What Is Grunt?

Grunt is a JavaScript task runner, which can automate tasks like minification, compilation, unit testing, checking js errors. Once configured, one doesn’t have to worry about these tasks.

What Are Grunt Modules/plugins?

Grunt modules are distributed through Node’s NPM directory. Normally, they are prefixed with grunt- and official grunt plugins are prefixed with grunt-contrib. Example: grunt-contrib-uglify. You can get list of all grunt plugins here.


Where Do You Define Configuration Of Grunt Plugin?

Grunt plugin configuration needs to be defined within grunt.initConfig method. See below sample code.

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
    // concat task configuration goes here.
    },
   uglify: {
    // uglify task configuration goes here.
   }
  });
};
Above code configures concat and uglify tasks.

Can You Override Default Settings Of A Plugin? If Yes, Then How?

Yes, we can override. Inside a task configuration, an options property may be specified to override built-in defaults. In addition, each target may have an options property which is specific to that target.

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
     options: {
        separator: ';'
      }
    }
  });
};

What Is A Task In Grunt?

Tasks are grunt’s bread and butter. Every time Grunt is run, you specify one or more tasks to run, which tells Grunt what you’d like it to do. See below code.

grunt.initConfig({
  concat: {
    development: {
      // concat task "development" target options and files go here.
    },
    production: {
      // concat task "production" target options and files go here.
    },
  },
  uglify: {
    development: {
      // uglify task "development" target options and files go here.
    },
  },
});

Here, there are 2 tasks defined concat and uglify. And for each task, we defined targets. For concat, there are 2 targets “development” and “production” and only “development” for uglify. Creating target allows us to define separate settings for different objectives. Here, we can have different option for development and production version. It’s not compulsory to define a target.



Target’s can also have their own option parameters which will override the settings of options defined for the task.

How Do You Install A Grunt Plugin?

The syntax remains name but the only thing which changes is module/plugin name.

npm install --save-dev
For example, to install uglify plugin:

npm install grunt-contrib-uglify --save-dev
By default, it always installs the latest version available. But if you wish to install specific version then same you can include in the command.

npm install @version --save-dev

Grunt Advanced Experienced Freshers Interview Questions Answers
Grunt Experienced Freshers Interview Questions Answers

How Do You Uninstall Grunt?

Run following command to uninstall grunt.

npm uninstall grunt
And if you wish to remove it from package.json, then use --save-dev option.

npm uninstall --save-dev grunt


Why To Use Grunt?

Grunt has become very popular and has tons of plugins to choose from. These plugins are great assets for any app to automate various things with minimum efforts.

How Do You Install Grunt?

Grunt and Grunt plugins are installed and managed via npm, the Node.js package manager. To install grunt, first ensure the npm is installed properly. And then run following command.

npm install grunt --save-dev
Please note, --save-dev is optional.


What Does ~ (tilde) Sign Means In Package.json?

In the simplest terms, the tilde matches the most recent minor version (the middle number). ~1.2.3 will match all 1.2.x versions but will miss 1.3.0. The caret, on the other hand, is more relaxed. It will update you to the most recent major version (the first number). ^1.2.3 will match any 1.x.x release including 1.3.0, but will hold off on 2.0.0.

You can also define the exact version number that you wish to use like “1.3.5” or to always use latest version, simply use latest or *.

How Do You Setup/configure Grunt?

Once installed, you need to add 2 files to setup Grunt.

1. package.json: This file is used by npm to store metadata for projects published as npm modules. So basically, there will be list of all Grunt plugins, along with grunt which your project is using.

2. Gruntfile: This file is named Gruntfile.js and is used to configure or define tasks and load Grunt plugins.

What Is --save-dev Option While Installing The Grunt?

As mentioned in previous answer that “package.json” file holds the metadata for grunt plugins. So when grunt is installed using --save-dev option, the metadata is added to package.json. So you don’t have to add it manually. And this is how your package.json will look like,

{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-uglify": "~0.5.0"
  }
}

What Is The Difference Between --save And --save-dev?

Before will look at the difference, it is important to understand the difference between dependencies and devDependencies.

devDependencies are for the development-related scripts, e.g. unit testing, packaging scripts, documentation generation, etc. where dependencies are required for production use, and assumed required for dev as well. As for example, you can include some plugin which you require during development like (for debugging or unit testing) but you don’t need them on production.

So --save adds packages under dependencies and --save-dev adds under devdependencies section.

{
  "name": "my-project-name",
  "version": "0.1.0",
  "dependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-uglify": "~0.5.0"
  }
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
  }
}


Which Are The Most Used Grunt Plugins?

Though there are tons of plugins which you can use, but below are the most used.

watch: Run predefined tasks whenever watched file patterns are added, changed or deleted.
jshint: Validate files with JSHint
uglify: Minify files with UglifyJS
concat: Concatenate files.
cssmin: Minify CSS
less: Compile LESS files to CSS.
Below is a sample gruntfile.js for your reference.

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['src/**/*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
      options: {
        // options here to override JSHint defaults
        globals: {
          jQuery: true,
          console: true,
          module: true,
          document: true
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.registerTask('test', ['jshint']);
  grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
};

What Is Grunt-cli?

Grunt cli is command line interface to run grunt commands. In other words, it’s a tool to access Grunt from command line anywhere in the system. To install, grunt –cli execute following command

npm install -g grunt-cli

This will put the grunt command in your system path, allowing it to be run from any directory. Please note, that installing grunt-cli, doesn’t install grunt on your system.

-g means global which means it adds to PATH variables of the system so that you can run grunt from anywhere (without going to specific folder on command prompt).

The reason for having two components is to ensure that we can run different grunt versions side-by-side (i.e. legacy versions in older projects). Hence it is recommended to install grunt-cli globally while grunt should be installed on a per-project basis.

How Does Gruntfile.js Uses Package.json?

Task configuration is specified in your Gruntfile via the grunt.initConfig method. Inside of grunt.initConfig(), we read the information from package.json and saved it to a pkg property. With this, we can use the attributes from our package.json file. We can call the name of our project using pkg.name and the version with pkg.version.

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json')
  });
};

How Do You Execute Grunt Task?

You can execute the grunt task from command line. Remember, we have grunt command line interface. To execute contact module with grunt for all the tasks.

grunt concat

To execute task with particular target

grunt concat:development

How Do We Load Grunt Plugins In Gruntfile.js?

grunt.loadNpmTasks() is used for loading grunt plugins. Before loading, please ensure that these plugins are already installed via npm.

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

How To Run Multiple Tasks Together In Grunt?

Every grunt module may have defined a task. But running them individually can make things difficult for developers. What is one wants to run grunt uglify and grunt jshint together

Using grunt.registerTask(taskName, [description, ] taskList) we can group all the tasks under one roof. Task name can be anything of your choice, description is optional and task list is array of module tasks which you wish to execute. For example,

grunt.registerTask('development', ['jshint:development', 'concat:development', 'uglify:development']);

Above code creates a task named “development” and is asked to execute development target of “jshint”, “concat” and “uglify” packages. Similarly, you can register another task for production version.

grunt.registerTask('production', ['jshint:production', 'concat:production', 'uglify:production']);

Remember, you always need to define a default task.

grunt.registerTask('default', ['jshint', 'uglify', 'concat']);

Now, when you enter grunt on command prompt, it will execute the default task.

How To Get A Stack Trace When An Error Occurs?

Use the --stack option to see stack traces. Such as grunt task –stack.

Post a Comment

Previous Post Next Post