Gulp's task management system provides powerful orchestration capabilities for defining, composing, and executing build tasks. Built on the Undertaker library, it supports both sequential and parallel task execution with dependency management.
Register named tasks or retrieve previously registered tasks by name.
/**
* Register a named task or retrieve an existing task
* @param name - Task name
* @param fn - Task function (optional, omit to retrieve existing task)
* @returns Task function if retrieving, undefined if registering
*/
function task(name: string): Function;
function task(name: string, fn: Function): void;Usage Examples:
const gulp = require('gulp');
// Register a task
gulp.task('build:css', function() {
return gulp.src('src/**/*.scss')
.pipe(/* compile to CSS */)
.pipe(gulp.dest('dist/css/'));
});
// Register with async/await
gulp.task('build:js', async function() {
// async task implementation
});
// Register with callback
gulp.task('clean', function(done) {
// cleanup implementation
done();
});
// Retrieve a registered task
const cssTask = gulp.task('build:css');Compose tasks to run one after another in sequence.
/**
* Compose tasks to run in sequence
* @param tasks - Tasks to run sequentially (names or functions)
* @returns Combined task function
*/
function series(...tasks: (string | Function)[]): Function;Usage Examples:
const gulp = require('gulp');
// Simple series composition
const build = gulp.series('clean', 'build:css', 'build:js');
// Mixed task types
const deploy = gulp.series(
'test',
gulp.parallel('build:css', 'build:js'),
'minify',
'upload'
);
// With inline functions
const buildSequence = gulp.series(
function clean() {
// cleanup implementation
},
function compile() {
// compilation implementation
}
);
// Export for CLI usage
exports.build = build;Compose tasks to run simultaneously in parallel.
/**
* Compose tasks to run in parallel
* @param tasks - Tasks to run simultaneously (names or functions)
* @returns Combined task function
*/
function parallel(...tasks: (string | Function)[]): Function;Usage Examples:
const gulp = require('gulp');
// Simple parallel composition
const buildAssets = gulp.parallel('build:css', 'build:js', 'build:images');
// Nested composition
const build = gulp.series(
'clean',
gulp.parallel('build:css', 'build:js'),
'build:html'
);
// With inline functions
const processFiles = gulp.parallel(
function styles() {
return gulp.src('src/**/*.scss')
.pipe(/* transform */)
.pipe(gulp.dest('dist/'));
},
function scripts() {
return gulp.src('src/**/*.js')
.pipe(/* transform */)
.pipe(gulp.dest('dist/'));
}
);
// Export for CLI usage
exports.buildAssets = buildAssets;Watch files for changes and execute tasks when modifications occur.
/**
* Watch files for changes and execute tasks
* @param globs - Glob patterns to watch
* @param options - Watch configuration options
* @param task - Task function to execute on changes
* @returns Watcher instance for controlling the watch
*/
function watch(
globs: string | string[],
options?: WatchOptions,
task?: Function
): Watcher;
interface WatchOptions {
/** Whether to ignore initial file additions (default: true) */
ignoreInitial?: boolean;
/** Delay before triggering task after changes (ms) */
delay?: number;
/** Whether to queue task executions (default: true) */
queue?: boolean;
/** Additional options passed to chokidar */
[key: string]: any;
}
interface Watcher {
/** Stop watching files */
close(): void;
/** Add additional glob patterns to watch */
add(globs: string | string[]): void;
/** Remove glob patterns from watching */
unwatch(globs: string | string[]): void;
}Usage Examples:
const gulp = require('gulp');
// Basic file watching
function watchFiles() {
gulp.watch('src/**/*.scss', gulp.series('build:css'));
gulp.watch('src/**/*.js', gulp.series('build:js'));
}
// With options
function watchDev() {
gulp.watch('src/**/*.scss', {
delay: 500,
ignoreInitial: false
}, gulp.series('build:css'));
}
// Watch with inline task
gulp.watch('src/**/*.json', function(done) {
console.log('JSON file changed');
done();
});
// Advanced watcher control
function startWatch() {
const watcher = gulp.watch('src/**/*.js', buildJs);
// Add additional patterns later
watcher.add('lib/**/*.js');
// Remove patterns
watcher.unwatch('src/temp/**/*.js');
// Close watcher programmatically
// watcher.close();
return watcher;
}
// Export watch task
exports.watch = watchFiles;Advanced registry management for custom task storage and retrieval systems.
/**
* Get or set the task registry
* @param registry - Custom registry instance (optional)
* @returns Current registry if no parameter provided
*/
function registry(registry?: Registry): Registry | void;
interface Registry {
/** Get a task by name from the registry */
get(name: string): Function;
/** Set/register a task in the registry */
set(name: string, fn: Function): void;
/** Get all registered tasks as name-function pairs */
tasks(): { [name: string]: Function };
}Usage Examples:
const gulp = require('gulp');
// Get current registry
const currentRegistry = gulp.registry();
// Create custom registry (requires implementing Registry interface)
class CustomRegistry {
get(name) { /* implementation */ }
set(name, fn) { /* implementation */ }
tasks() { /* implementation */ }
}
// Set custom registry
gulp.registry(new CustomRegistry());
// List all registered tasks
const allTasks = gulp.registry().tasks();
console.log(Object.keys(allTasks)); // Array of task namesGet the dependency tree of registered tasks for debugging and visualization.
/**
* Get the dependency tree of registered tasks
* @param options - Tree generation options
* @returns Tree structure representing task dependencies
*/
function tree(options?: TreeOptions): TaskTree;
interface TreeOptions {
/** Show task dependencies (default: false) */
deep?: boolean;
}
interface TaskTree {
/** Display name for the task or task group */
label: string;
/** Type of node ('task', 'function', 'series', 'parallel') */
type: string;
/** Child nodes representing dependencies or sub-tasks */
nodes: TaskTree[];
}Usage Examples:
const gulp = require('gulp');
// Register some tasks first
gulp.task('clean', function() { /* ... */ });
gulp.task('build', gulp.series('clean', 'compile'));
gulp.task('compile', function() { /* ... */ });
// Get basic tree
const taskTree = gulp.tree();
console.log(taskTree);
// Output: { label: 'Tasks', type: 'root', nodes: [...] }
// Get detailed tree with dependencies
const detailedTree = gulp.tree({ deep: true });
console.log(JSON.stringify(detailedTree, null, 2));
// Use for task visualization or debugging
function printTaskTree(tree, indent = 0) {
const spaces = ' '.repeat(indent);
console.log(`${spaces}${tree.label} (${tree.type})`);
tree.nodes.forEach(node => printTaskTree(node, indent + 2));
}
printTaskTree(taskTree);Get timestamp information for incremental builds and change detection.
/**
* Get timestamp of last successful task run
* @param task - Task name or function
* @param timeResolution - Time resolution in milliseconds
* @returns Timestamp of last run or undefined if never run
*/
function lastRun(
task: string | Function,
timeResolution?: number
): number | undefined;Usage Examples:
const gulp = require('gulp');
// Incremental builds using lastRun
function buildStyles() {
return gulp.src('src/**/*.scss', {
since: gulp.lastRun(buildStyles)
})
.pipe(/* transform */)
.pipe(gulp.dest('dist/'));
}
// Use in watch tasks for efficient rebuilds
function watchStyles() {
gulp.watch('src/**/*.scss', buildStyles);
}
// Check if task has run before
function conditionalTask() {
const lastRun = gulp.lastRun('build:css');
if (!lastRun) {
console.log('First time running build:css');
} else {
console.log(`Task last ran at: ${new Date(lastRun)}`);
}
// ... task implementation
}
// Use with named tasks
gulp.task('compile', function() {
return gulp.src('src/**/*.ts', {
since: gulp.lastRun('compile')
})
.pipe(/* compile */)
.pipe(gulp.dest('dist/'));
});
// Compare timestamps for conditional processing
function smartBuild() {
const stylesLastRun = gulp.lastRun('build:styles');
const scriptsLastRun = gulp.lastRun('build:scripts');
if (!stylesLastRun || (scriptsLastRun && stylesLastRun < scriptsLastRun)) {
console.log('Styles need rebuilding');
return gulp.series('build:styles', 'build:scripts')();
}
return gulp.series('build:scripts')();
}Gulp supports different types of task functions:
function streamTask() {
return gulp.src('src/**/*.js')
.pipe(/* transform */)
.pipe(gulp.dest('dist/'));
}async function promiseTask() {
const result = await someAsyncOperation();
return result;
}function callbackTask(done) {
// do some work
done(); // signal completion
}
function errorTask(done) {
done(new Error('Task failed')); // signal error
}function spawnTask() {
return spawn('npm', ['run', 'test'], { stdio: 'inherit' });
}