Thursday, April 21, 2016

How to install and use Grunt


This article depicts simplified steps to install and use Grunt. For more information about Grunt please go through following articles click here and here.

1. Go to https://nodejs.org/en/download/ to download and install node.js on your machine.
2. Go to command prompt and run following command which should display the node version installed on your machine.
node -v
3. Type npm to check node package manager is installed.
4. Install latest npm using following command
npm install npm –g
5. Run following command to Grunt's command line interface (CLI) globally.
npm install -g grunt-cli
6. In the command prompt using cd command, navigate to the project directory folder.
7. Now run following command to create default project.jason file.
npm init –f
8. Run following command to install latest version of grunt in your project. It will create node_modules folder in your project.
npm install grunt --save-dev
9. Now we will see configure grunt task to minify js file. For this install grunt-contrib-uglify plugin using following command.
npm install grunt-contrib-uglify --save-dev
10. After running above command you can observe following:-
         a. Another folder created inside node_modules folder with name grunt-contrib-uglify. Similarly you can install any plugin from npm.
         b. Package.json file is updated with
11. Now create a gruntfile.js in the same location where package.json exist (this is root folder of project).
12. Copy following code in to gruntfile.js

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']);

};

13. Now create src folder and create a js file with some js code. File name should be same as package name. Open package.json and check name property.
14. Now in the command prompt run following command
Grunt
15. This will create a minified file of js in to build folder.

No comments:

Post a Comment