Taming Gruntfiles
Every software project needs plumbing.
If you write your code in JavaScript chances are you’re using Grunt. And if your project has been around long enough, chances are your Gruntfile is huge. Even though you write comments and indent properly, the configuration is starting to look unwieldy and is hard to navigate and maintain (see ngbp’s Gruntfile for an example).
Enter load-grunt-config, a Grunt plugin that lets you break up your Gruntfile by task (or task group), allowing for a nice navigable list of small per-task Gruntfiles.
When used, your Grunt config file tree might look like this:
./
|_ Gruntfile.coffee
|_ grunt/
|_ aliases.coffee
|_ browserify.coffee
|_ clean.coffee
|_ copy.coffee
|_ watch.coffee
|_ test-group.coffee
watch.coffee
, for example, might be:
module.exports = {
sources:
files: [
'<%= buildDir %>/**/*.coffee',
'<%= buildDir %>/**/*.js'
]
tasks: ['test']
html:
files: ['<%= srcDir %>/**/*.html']
tasks: ['copy:html', 'test']
css:
files: ['<%= srcDir %>/**/*.css']
tasks: ['copy:css', 'test']
img:
files: ['<%= srcDir %>/img/**/*.*']
tasks: ['copy:img', 'test']
}
and aliases.coffee
:
module.exports = {
default: [
'clean'
'browserify:libs'
'browserify:dist'
]
dev: [
'clean'
'connect'
'browserify:libs'
'browserify:dev'
'mocha_phantomjs'
'watch'
]
}
By default, load-grunt-config
reads the task configurations from the grunt/
folder located on the same level as your Gruntfile
. If there’s an alias.js|coffee|yml
file in that directory, load-grunt-config
will use it to load your task aliases (which is convenient because one of the problem with long Gruntfiles is that the task aliases are hard to find).
Other files in the grunt/
directory define configurations for a single task (e.g. grunt-contrib-watch
) or a group of tasks.
Another nice thing is that load-grunt-config
takes care of loading plugins; it reads package.json
and automatically loadNpmTasks
s all the grunt plugins it finds for you.
To sum it up, for a bigger project, your Gruntfile can get messy. load-grunt-config
helps combat that by introducing structure into the build configuration, making it more readable and maintainable.
Happy grunting!