I started using Grunt.js by reading their easy to follow tutorial. Then, I created a Gruntfile.js inside of my theme’s js directory “sites/all/themes/mytheme/js/Gruntfile.js
”:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
main: {
src: [
'src/*.js',
],
dest: 'production.js'
}
},
uglify: {
build: {
files: {
'production.min.js': 'production.js',
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/*.js'],
options: {
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
watch: {
files: ['src/*.js'],
tasks: ['concat', 'jshint', 'uglify']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('test', ['concat', 'jshint']);
grunt.registerTask('default', ['concat', 'jshint', 'uglify']);
};
My Gruntfile does 3 things for me (right now):
- Combines smaller, more manageable files inside
src/
into one file.
- Checks for errors in my compiled file.
- Compresses my file when I’m ready for production.
All I have to do is run grunt watch
from the terminal and whenever one of the files inside src/
is changed my production.js
file is updated and compressed. When I’m all done debugging I just change the following in my .info file:
scripts[] = js/production[.min].js
This results in faster page loads because only one (smaller) request is being performed as opposed to many uncompressed file requests.