Core task registration and execution system supporting basic tasks, multi-tasks with targets, and initialization tasks. Provides lifecycle hooks, dependency management, and asynchronous task execution.
Register different types of tasks for build automation and workflow management.
/**
* Register a basic task that executes a single function
* @param {string} name - Task name used for CLI execution
* @param {string} [info] - Optional task description for help
* @param {function} fn - Task function to execute
*/
grunt.registerTask = function(name, info, fn) {};
/**
* Register a multi-task that can have multiple targets
* @param {string} name - Task name used for CLI execution
* @param {string} [info] - Optional task description for help
* @param {function} fn - Task function executed for each target
*/
grunt.registerMultiTask = function(name, info, fn) {};
/**
* Register an initialization task for project setup
* @param {string} name - Task name
* @param {string} [info] - Task description
* @param {function} fn - Initialization function
*/
grunt.registerInitTask = function(name, info, fn) {};
/**
* Rename an existing task
* @param {string} oldname - Current task name
* @param {string} newname - New task name
*/
grunt.renameTask = function(oldname, newname) {};Query and manage registered tasks.
/**
* Check if a task exists
* @param {string} name - Task name to check
* @returns {boolean} True if task exists
*/
grunt.task.exists = function(name) {};
/**
* Check if a task is an alias task
* @param {string} name - Task name to check
* @returns {boolean} True if task is an alias
*/
grunt.task.isTaskAlias = function(name) {};
/**
* Parse command-line arguments into task names
* @param {Array} args - Command-line arguments
* @returns {string[]} Array of task names
*/
grunt.task.parseArgs = function(args) {};
/**
* Split argument string into individual arguments
* @param {string} str - Argument string
* @returns {string[]} Array of arguments
*/
grunt.task.splitArgs = function(str) {};
/**
* Normalize multi-task file configuration
* @param {object} data - File configuration data
* @param {string} target - Target name
* @returns {Array} Normalized file objects
*/
grunt.task.normalizeMultiTaskFiles = function(data, target) {};Usage Examples:
// Basic task
grunt.registerTask('hello', 'Say hello', function() {
grunt.log.writeln('Hello World!');
});
// Multi-task with targets
grunt.registerMultiTask('concat', 'Concatenate files', function() {
const options = this.options({
separator: '\n'
});
this.files.forEach(function(fileObj) {
const src = fileObj.src.filter(function(filepath) {
return grunt.file.exists(filepath);
});
const content = src.map(function(filepath) {
return grunt.file.read(filepath);
}).join(options.separator);
grunt.file.write(fileObj.dest, content);
grunt.log.writeln('File "' + fileObj.dest + '" created.');
});
});
// Asynchronous task
grunt.registerTask('async-task', 'An async task', function() {
const done = this.async();
setTimeout(function() {
grunt.log.writeln('Async operation completed');
done();
}, 1000);
});Load tasks from external sources including npm modules and file system directories.
/**
* Load tasks from an npm module
* @param {string} name - Module name (e.g., 'grunt-contrib-concat')
*/
grunt.loadNpmTasks = function(name) {};
/**
* Load tasks from a directory
* @param {string} tasksdir - Directory path containing task files
*/
grunt.loadTasks = function(tasksdir) {};Usage Examples:
// Load tasks from npm module
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Load custom tasks from directory
grunt.loadTasks('tasks');
grunt.loadTasks('./build/custom-tasks');Execute tasks programmatically or manage task execution flow.
/**
* Execute tasks programmatically
* @param {string[]} tasks - Array of task names to execute
* @param {object} [options] - Execution options
* @param {function} [done] - Completion callback
*/
grunt.tasks = function(tasks, options, done) {};
/**
* Add tasks to the execution queue
* @param {...string} tasks - Task names to queue
*/
grunt.task.run = function(...tasks) {};
/**
* Mark a position in the task queue
*/
grunt.task.mark = function() {};
/**
* Clear tasks from queue
* @param {object} [options] - Clear options
* @param {boolean} [options.untilMarker] - Clear only until marker
*/
grunt.task.clearQueue = function(options) {};
/**
* Start task execution
* @param {object} [options] - Start options
* @param {boolean} [options.asyncDone] - Use async completion
*/
grunt.task.start = function(options) {};
/**
* Require that specified tasks have run successfully
* @param {...string} tasks - Task names
*/
grunt.task.requires = function(...tasks) {};
/**
* Run all targets for a multi-task
* @param {string} taskname - Multi-task name
* @param {string[]} [args] - Task arguments
*/
grunt.task.runAllTargets = function(taskname, args) {};Usage Examples:
// Programmatic execution
grunt.tasks(['clean', 'concat', 'uglify'], {force: true}, function() {
console.log('Build completed!');
});
// Inside a task, require other tasks to have run
grunt.registerTask('deploy', function() {
grunt.task.requires('build test');
// Deploy logic here
});Properties and methods available within task functions via the this keyword.
// Task context object (available as 'this' in task functions)
const taskContext = {
/**
* Mark task as asynchronous and return completion callback
* @returns {function} Callback to signal task completion
*/
async: function() {},
/**
* Get task options merged with defaults
* @param {object} [defaults] - Default option values
* @returns {object} Merged options
*/
options: function(defaults) {},
/**
* Require that other tasks have run successfully
* @param {string} tasks - Space-separated task names
*/
requires: function(tasks) {},
/**
* Require that configuration properties exist
* @param {string} props - Space-separated property paths
*/
requiresConfig: function(props) {},
/** Current task name */
name: string,
/** Task name with arguments */
nameArgs: string,
/** Array of task arguments */
args: Array,
/** Object of arguments as boolean flags */
flags: Object,
/** Current target name (multi-tasks only) */
target: string,
/** Current target data (multi-tasks only) */
data: any,
/** Normalized files array (multi-tasks only) */
files: Array,
/** Flattened source files array (multi-tasks only) */
filesSrc: Array,
/** Number of errors logged during task execution */
errorCount: number
};Usage Examples:
grunt.registerMultiTask('process', function() {
// Get options with defaults
const options = this.options({
encoding: 'utf8',
separator: '\n'
});
// Check required configuration
this.requiresConfig('process.' + this.target + '.files');
// Access task properties
grunt.log.writeln('Processing target: ' + this.target);
grunt.log.writeln('Task arguments: ' + this.args.join(', '));
// Process files
this.files.forEach(function(fileObj) {
// File processing logic
});
// Check for errors
if (this.errorCount > 0) {
grunt.fail.warn('Task completed with errors');
}
});
// Asynchronous task
grunt.registerTask('fetch-data', function() {
const done = this.async();
// Async operation
fetchRemoteData()
.then(function(data) {
grunt.file.write('data.json', JSON.stringify(data));
done();
})
.catch(function(error) {
grunt.fail.warn('Failed to fetch data: ' + error.message);
done(false);
});
});Utilities for processing files within multi-tasks.
// File object structure in multi-tasks
const fileObject = {
/** Array of source file paths */
src: Array,
/** Destination file path */
dest: string,
/** Original file specification object */
orig: Object
};Usage Examples:
grunt.registerMultiTask('compile', function() {
this.files.forEach(function(fileObj) {
// Filter existing source files
const validSrc = fileObj.src.filter(function(filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
}
return true;
});
// Process each source file
const compiled = validSrc.map(function(filepath) {
const content = grunt.file.read(filepath);
return compileContent(content);
}).join('\n');
// Write compiled output
grunt.file.write(fileObj.dest, compiled);
grunt.log.writeln('File "' + fileObj.dest + '" created.');
});
});Task-level error handling and reporting mechanisms.
/**
* Log warning and optionally abort execution
* @param {string|Error} error - Error message or Error object
* @param {number} [errorcode] - Exit code
*/
grunt.warn = function(error, errorcode) {};
/**
* Log fatal error and abort execution
* @param {string|Error} error - Error message or Error object
* @param {number} [errorcode] - Exit code
*/
grunt.fatal = function(error, errorcode) {};Usage Examples:
grunt.registerTask('validate', function() {
if (!grunt.file.exists('config.json')) {
grunt.fail.warn('Configuration file not found');
return false;
}
try {
const config = grunt.file.readJSON('config.json');
if (!config.version) {
grunt.fail.fatal('Configuration missing required version field');
}
} catch (e) {
grunt.fail.fatal('Invalid configuration file: ' + e.message);
}
});