Grunt is a JavaScript task runner that automates repetitive development tasks like minification, compilation, unit testing, linting, and more. It provides a command-line interface and a robust plugin ecosystem that allows developers to configure and run custom build processes through a Gruntfile.js configuration.
npm install gruntconst grunt = require('grunt');For ES modules (when supported):
import grunt from 'grunt';const grunt = require('grunt');
// Basic task registration
grunt.registerTask('hello', 'A basic task', function() {
grunt.log.writeln('Hello from Grunt!');
});
// Multi-task registration with targets
grunt.registerMultiTask('process', 'Process files', function() {
this.files.forEach(function(fileObj) {
grunt.log.writeln('Processing: ' + fileObj.src.join(', '));
});
});
// Configuration initialization
grunt.initConfig({
process: {
dev: {
files: {
'dist/app.js': ['src/*.js']
}
}
}
});
// Programmatic task execution
grunt.tasks(['hello', 'process:dev'], {}, function() {
grunt.log.writeln('All tasks completed!');
});Grunt is built around several key components:
Core task registration and execution system supporting basic tasks, multi-tasks with targets, and initialization tasks. Provides lifecycle hooks and dependency management.
/**
* Register a basic task
* @param {string} name - Task name
* @param {string} [info] - Task description
* @param {function} fn - Task function
*/
grunt.registerTask = function(name, info, fn) {};
/**
* Register a multi-task with targets
* @param {string} name - Task name
* @param {string} [info] - Task description
* @param {function} fn - Task function
*/
grunt.registerMultiTask = function(name, info, fn) {};
/**
* Load tasks from npm module
* @param {string} name - Module name
*/
grunt.loadNpmTasks = function(name) {};
/**
* Execute tasks programmatically
* @param {string[]} tasks - Array of task names
* @param {object} [options] - Execution options
* @param {function} [done] - Completion callback
*/
grunt.tasks = function(tasks, options, done) {};Centralized configuration system with template processing, deep property access, and data validation. Supports complex nested configurations and runtime data manipulation.
/**
* Initialize configuration data
* @param {object} config - Configuration object
*/
grunt.initConfig = function(config) {};
/**
* Get or set configuration property
* @param {string} [prop] - Property path (dot notation)
* @param {*} [value] - Value to set
* @returns {*} Property value or entire config
*/
grunt.config = function(prop, value) {};
/**
* Process templates in configuration values
* @param {*} value - Value to process
* @returns {*} Processed value
*/
grunt.config.process = function(value) {};Comprehensive file system operations with glob pattern support, encoding handling, and cross-platform path utilities. Includes reading, writing, copying, and directory manipulation.
/**
* Read file contents
* @param {string} filepath - Path to file
* @param {object} [options] - Read options
* @returns {string} File contents
*/
grunt.file.read = function(filepath, options) {};
/**
* Write file contents
* @param {string} filepath - Path to file
* @param {string} contents - Content to write
* @param {object} [options] - Write options
*/
grunt.file.write = function(filepath, contents, options) {};
/**
* Expand glob patterns to file paths
* @param {object} [options] - Glob options
* @param {string|string[]} patterns - Glob patterns
* @returns {string[]} Matching file paths
*/
grunt.file.expand = function(options, patterns) {};Lodash-based template engine with custom delimiters, date utilities, and configuration integration. Supports complex template processing with runtime data binding.
/**
* Process template with data
* @param {string} template - Template string
* @param {object} [options] - Processing options
* @returns {string} Processed template
*/
grunt.template.process = function(template, options) {};
/**
* Format current date
* @param {string} [format] - Date format string
* @returns {string} Formatted date
*/
grunt.template.today = function(format) {};Command-line interface with option parsing, help system, task discovery, and execution control. Supports various CLI flags and runtime configuration.
/**
* Get or set command-line option
* @param {string} key - Option key
* @param {*} [value] - Option value to set
* @returns {*} Option value
*/
grunt.option = function(key, value) {};
/**
* Display help information
*/
grunt.help.display = function() {};EventEmitter2-based event system with wildcard support for task lifecycle and custom events.
/**
* Register event listener
* @param {string} event - Event name (supports wildcards)
* @param {function} listener - Event handler function
*/
grunt.event.on = function(event, listener) {};
/**
* Emit event with arguments
* @param {string} event - Event name
* @param {...*} args - Event arguments
*/
grunt.event.emit = function(event, ...args) {};Comprehensive error and warning system with different severity levels, error counting, and structured error reporting.
/**
* Issue a warning without stopping execution
* @param {string|Error} message - Warning message or Error object
* @param {number} [errcode] - Optional error code
*/
grunt.warn = function(message, errcode) {};
/**
* Issue a fatal error and stop execution
* @param {string|Error} message - Error message or Error object
* @param {number} [errcode] - Optional error code
*/
grunt.fatal = function(message, errcode) {};
/**
* Current number of errors logged
*/
grunt.fail.errorcount: number;Command-line option parsing and runtime configuration management.
/**
* Get or set command-line option
* @param {string} key - Option key
* @param {*} [value] - Option value to set
* @returns {*} Option value
*/
grunt.option = function(key, value) {};
/**
* Get all available option flags
* @returns {string[]} Array of option flags
*/
grunt.option.flags = function() {};Access to essential utility libraries and helper functions used throughout Grunt.
/**
* Lodash utility library
*/
grunt.util._: object;
/**
* Async utility functions
*/
grunt.util.async: object;
/**
* Enhanced typeof with additional type detection
* @param {*} value - Value to check
* @returns {string} Type string
*/
grunt.util.kindOf = function(value) {};
/**
* Convert arguments to array
* @param {*} obj - Object to convert
* @returns {Array} Converted array
*/
grunt.util.toArray = function(obj) {};Multi-level logging with verbose mode, colored output, and structured reporting.
/**
* Write message with newline
* @param {string} [msg] - Message to write
*/
grunt.log.writeln = function(msg) {};
/**
* Write success message
* @param {string} msg - Success message
*/
grunt.log.ok = function(msg) {};
/**
* Write error message
* @param {string} msg - Error message
*/
grunt.log.error = function(msg) {};
/**
* Write warning message
* @param {string} msg - Warning message
*/
grunt.log.warn = function(msg) {};// Task context (available as 'this' inside task functions)
const taskContext = {
/** Mark task as asynchronous and return done callback */
async: function() {},
/** Get task options merged with defaults */
options: function(defaults) {},
/** Require other tasks to have run successfully */
requires: function(...tasks) {},
/** Require configuration properties to exist */
requiresConfig: function(...props) {},
/** Current task name */
name: string,
/** Task name with arguments */
nameArgs: string,
/** Task arguments array */
args: Array,
/** Arguments as boolean flags */
flags: Object,
/** Current target (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 during task execution */
errorCount: number
};
// File object structure
const fileObject = {
/** Source file paths */
src: Array,
/** Destination file path */
dest: string,
/** Original file specification */
orig: Object
};
// File mapping structure for expandMapping
const fileMapping = {
/** Source file path */
src: string,
/** Destination file path */
dest: string
};
// Configuration options
const configOptions = {
/** Template processing data */
data: Object,
/** Custom template delimiters */
delimiters: string
};
// File read/write options
const fileOptions = {
/** File encoding (default: 'utf8') */
encoding: string,
/** File mode for writing */
mode: number
};
// File expansion options
const expandOptions = {
/** Filter function for files */
filter: function|string,
/** Current working directory */
cwd: string,
/** Include dotfiles */
dot: boolean,
/** Match base path */
matchBase: boolean,
/** Follow symbolic links */
follow: boolean
};
// Error codes
const errorCodes = {
FATAL_ERROR: 1,
MISSING_GRUNTFILE: 2,
TASK_FAILURE: 3,
TEMPLATE_ERROR: 4,
INVALID_AUTOCOMPLETE: 5,
WARNING: 6
};