How to split a Gruntfile into multiple files

Task runners such as Grunt or Gulp can immensely speed up development, while also increasing the reliability of the code you’re writing.

The problem is that their configuration files tend to grow easily, even for small projects, and they can become hard to maintain pretty quickly.

The ones we’ve used back at my company so far follow the same path, so we though about finding a way to split them. Turns out, there is a way of doing so, and a quick search on Google returned more than one method to do it.

I’ve created a public Gist that summarizes what I’ve found.

Going in a little more detail about it, most notably here’s what I have discovered:

  • The load-grunt-tasks module allows you to automatically load the tasks you need, without having to call grunt.loadNpmTasks for each one of them; just add the tasks to the package.json file, and you’re good.
  • The loadConfig function (got the idea from Thomas Boyt) takes care of reading each configuration files that are put in a specific folder, such as tasks/options. Each file must be named as the task its declaring the configuration for (so uglify.js, for example). After reading each file, the only thing left to do is extending the main configuration object:
    grunt.util._.extend( config, loadConfig( "./tasks/options/" ) );
  • Grunt can already do the same for tasks definitions with the grunt.loadTasks( "tasks" ); instruction, which opens the tasks folder and looks for files containing tasks definitions.

So, in conclusion, just like I’m not looking back after having discovered what task runners can do for our projects, I doubt I’ll ever follow the single Gruntfile.js approach again.

Leave a Reply