Sample Grunt files to manage your tasks with grunt

If you don't have a clear idea about what is Grunt and what is it used for please check my previous blog post about Grunt.

gruntfile.js file for auto execute a nodeJs script after a change in the code

module.exports = function (grunt) {
  grunt.initConfig({
    
    //create task execute
    execute: {
      target: {
        src: ['connectNode.js']
      }
    },
    //watch for changes in connectNode.js file and execute the task "execute"
    watch: {
      scripts: {
        files: ['connectNode.js'],
        tasks: ['execute'],
      },
    }
  });

  //loading necessary node packages
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-execute');
};
Note: Here name of our working file is connectNode.js and you should have installed node packages "grunt-contrib-watch" and "grunt-execute".

gruntfile.js file for auto minify JavaScript files script after a change in the code

module.exports = function (grunt) {
 //load node packages
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');   
    
    grunt.initConfig({
  //create task uglify for minify javaScript
        uglify:{
            my_target:{
                files:{
                    'script.js':['js/*.js']
                }
            }
        }, 
  //create task watch to watch for a change in "js" directory and execute task "uglify" 
        watch:{            
            scripts:{
                files:['js/*.js'],
                tasks:['uglify']
            }    
        }        
    });
}


Here grunt will look for any JavaScript file in "js" directory and minify them in to a script.js file

gruntfile.js file for auto auto reload HTML files into a browser after a change in the code

module.exports = function (grunt) {
 //load node packages
    grunt.loadNpmTasks('grunt-contrib-watch');  

    grunt.initConfig({
 //create task watch to look for change of HTML and reload
        watch:{
            options:{livereload:true},            
            html:{
                files:['*.html'],
            }         
        }        
    });  
}

Here grunt will reload any loaded HTML after any change in HTML code

Note: <script src="http://localhost:35729/livereload.js"></script>
This script tag should be included in your HTML pages to auto reload.

No comments:

Post a Comment