Configuring Grunt

Configuring Grunt

grunt logo

Configuring Grunt

Check this post to know how to install Grunt. Grunt has main script file called Gruntfile.js. It is a nodejs module – means that you are free to use all power of nodejs there.

The module is wrapped up with this construction:

module.exports = function(grunt) {
    .....
    some code here
    .....
}

We pass grunt object inside the module for further usage.

Let’s look closer how to use it.

Copying files

The very basic operation is copying a file from one location to another. For example you need to copy a font file to some temporary directory before uploading it to CDN. You should use grunt-contrib-copy task plugin for that.

Lets update Gruntfile.js module. First of all add the plugin config to grunt config:

module.exports = function(grunt) {
  grunt.initConfig({
    copy: {
        fonts: {
            expand: true,
            cwd: 'app/fonts/',
            src: ['**'],
            dest: 'temp/fonts'
        }
    }

  });
 ....
};

where:

  • cwd – change current working directory to the path specified
  • src – relative path to the target files from the folder specified in cwd
  • dest – destination directory

Then you must to load grunt task module:

module.exports = function(grunt) {
  grunt.initConfig({
    copy: {
        fonts: {
            expand: true,
            cwd: 'app/fonts/',
            src: ['**'],
            dest: 'temp/fonts'
        }
    }

  });
  grunt.loadNpmTasks('grunt-contrib-copy');
  ....
};

Notice that you should put grunt.loadNpmTasks line outside grunt.initConfig method call.

Finally you need to add “copy” task to the grunt default task list:

module.exports = function(grunt) {
  grunt.initConfig({
    copy: {
        fonts: {
            expand: true,
            cwd: 'app/fonts/',
            src: ['**'],
            dest: 'temp/fonts'
        }
    }

  });
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.registerTask('default', ['copy']);
};

where:

  • default – is the title of grunt task list. “Default” list will be called when you run grunt command without any task name
  • [‘copy’] – tasks in this araay will run in respective order.

The config is ready, but if you run grunt command now you will see error:

>> Local Npm module "grunt-contrib-copy" not found. Is it installed?
Warning: Task "copy" not found. Use --force to continue.

That means you haven’t installed grunt-contrib-copy module. Install it with npm:

npm install grunt-contrib-copy

Conclusion

I hope this is very configuration example will help you to start working. Check other posts to see more interesting cases.

Author: vlad