Grunt How To Create A Hello World Project

Do you like this?

Summary:
This short tutorial shows you how to create a new Grunt project from scratch.


Content:

We are going to build a hello app in grunt with grunt-contrib-connect which will act as our server instead of any HTTP servers such as Tomcat, and grunt-contrib-watch which will watch for our files' changes and refresh the browser to reflect the changes. The project will use npm which manages all the node packages, and grunt which is equivalent to build files such as Maven.

  1. Install NodeJs. It will also install Node Package Manager (NPM). Download NodeJs
  2. mkdir hello-grunt
  3. cd hello-grunt
  4. npm init
  5. npm install -g grunt-cli
  6. npm install grunt --save-dev
  7. npm install grunt-contrib-connect --save-dev
  8. npm install grunt-contrib-watch --save-dev
  9. Create a file named Gruntfile.js with the following content:
    'use strict';
    
    var config= {
    	app_folder: 'app',
    };
    
    module.exports= function(grunt){
    
    	grunt.initConfig({
    
    		config: config,
    
    		watch: {
    			livereload: {
    				options: {
    					livereload: '<%= connect.livereload.options.livereload %>'
    				},
    				files: [
    				  '<%= config.app_folder %>/**'
    				]
    			}
    		},
    
    		connect: {
    			livereload: {
    				options:{
    					port: 9000,
    					hostname: 'localhost',
    					open: true,
    					livereload:9999,
    					middleware: function(connect){
    						return [
    								connect.static(config.app_folder)
    						];
    					}
    				}
    			},
    		}
    
    	});
    
    	grunt.loadNpmTasks('grunt-contrib-watch');
    	grunt.loadNpmTasks('grunt-contrib-connect');
    
    	grunt.registerTask('serve',['connect:livereload','watch']);
    
    
    }		
    		
  10. Create a folder app to store all the javascript, css and html resources
  11. Create an index.html page with the tag. If not found, auto live reload will not work
  12. Run: grunt serve. Your browser should be fired up with the index.html page displayed. When you are editting the page, you can see the browser auto refreshes to reflect the new content

 
comments powered by Disqus