In many instances, our Gruntfile.js
file can become quite large and complicated, especially when we start including our own custom tasks into the mix. Grunt provides the means to split our custom tasks into their own individual files, thereby reducing the complexity of our Gruntfile.js
and increasing reusability, since this new task file could also be used in other Grunt projects. In Chapter 3, Using Grunt, we learnt how to use grunt.registerTask
to create our own custom tasks; however, to move these calls to registerTask
into another file, we will need a reference to the grunt
object (since grunt
is passed into our Gruntfile.js
).
This is exactly what the grunt.loadTasks
function does: it is called with a directory path as the argument, then runs every JavaScript file inside the given directory as if it were a "mini" Gruntfile.js
file (also passing it the current grunt
object). The following example demonstrates this:
//Code example 02-external-tasks // Gruntfile.js module.exports = function(grunt) { grunt.loadTasks("./tasks"); grunt.initConfig({ foo: { bar: 42 } }); grunt.registerTask("default", ["foo"]); }; // tasks/foo.js module.exports =function(grunt) { grunt.registerTask("foo", function() { console.log("foo says bar is: " + grunt.config("foo.bar")); }); };
In the example above, we are defining the foo
task in a foo.js
file, inside a tasks
directory. In addition to foo.js
, we could include as many other JavaScript files as we like and perform anything that we could do in our Gruntfile.js
.
3.142.250.203