Grunt Babel is a Grunt plugin that enables developers to transpile next-generation JavaScript code using Babel 7.x. It provides seamless integration between Grunt's build automation and Babel's transpilation capabilities, allowing developers to transform modern JavaScript syntax (ES2015+, JSX, TypeScript) into backward-compatible code for older browsers and environments.
npm install --save-dev grunt-babel @babel/core @babel/preset-envThe plugin is automatically loaded by Grunt when using load-grunt-tasks:
require('load-grunt-tasks')(grunt); // Loads grunt-babel automaticallyOr manually:
grunt.loadTasks('tasks'); // If grunt-babel is in node_modules/grunt-babel/tasksmodule.exports = function(grunt) {
grunt.initConfig({
babel: {
options: {
sourceMap: true,
presets: ['@babel/preset-env']
},
dist: {
files: {
'dist/app.js': 'src/app.js'
}
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['babel']);
};Grunt Babel follows a simple plugin architecture:
@babel/core.transformFileAsync() for file transformationThe plugin registers a multi-task named "babel" that transpiles JavaScript files using Babel.
/**
* Main plugin export function that registers the babel task with Grunt
* @param grunt - The Grunt instance to register the task with
*/
function gruntBabel(grunt: any): void;
/**
* Registered Grunt multi-task for Babel transpilation
* Task name: "babel"
* Description: "Use next generation JavaScript, today"
*/
grunt.registerMultiTask(taskName: "babel", description: string, taskFunction: Function);The babel task accepts standard Babel options plus Grunt-specific file configuration.
interface BabelTaskOptions {
/** Generate source maps for transpiled files */
sourceMap?: boolean;
/** Babel presets to apply during transpilation */
presets?: string[];
/** Babel plugins to apply during transpilation */
plugins?: string[];
/** Caller identification (automatically set to { name: "grunt-babel" }) */
caller?: { name: string; [key: string]: any };
/** Custom Babel options (any valid @babel/core option except filename/filenameRelative) */
[key: string]: any;
}
interface BabelTaskConfig {
/** Global options applied to all targets */
options?: BabelTaskOptions;
/** Individual build targets */
[targetName: string]: {
/** Babel options specific to this target */
options?: BabelTaskOptions;
/** File mappings: destination -> source or destination -> [sources] */
files: { [dest: string]: string | string[] } | Array<{
src: string[];
dest: string;
}>;
};
}Usage Example:
grunt.initConfig({
babel: {
options: {
sourceMap: true,
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-arrow-functions']
},
// Single file target
app: {
files: {
'dist/app.js': 'src/app.js'
}
},
// Multiple files target
components: {
files: {
'dist/component1.js': 'src/component1.js',
'dist/component2.js': 'src/component2.js'
}
},
// Using expand pattern for directory processing
all: {
files: [{
expand: true,
cwd: 'src/',
src: ['**/*.js'],
dest: 'dist/',
ext: '.js'
}]
},
// Target-specific options override global options
modernOnly: {
options: {
presets: [['@babel/preset-env', { targets: { node: '14' } }]]
},
files: {
'dist/modern.js': 'src/modern.js'
}
}
}
});The plugin generates the following output files:
interface BabelOutput {
/** Transpiled JavaScript file at the specified destination */
transpiledFile: string;
/** Source map file (when sourceMap option is true) */
sourceMapFile?: string; // destination + '.map'
}Output Behavior:
files configurationsourceMap: true option is set.map extension appended to the destination filename{ name: "grunt-babel" } for Babel plugin identificationThe plugin provides specific error handling for common configuration issues:
interface BabelErrors {
/** Thrown when @babel/core is not installed */
MISSING_BABEL_CORE: Error;
/** Thrown when trying to use Babel 6.x with grunt-babel v8 */
INCOMPATIBLE_BABEL_VERSION: Error;
/** Thrown when Babel transpilation fails */
TRANSPILATION_ERROR: Error;
}Error Messages:
@babel/core: Provides guidance to install correct Babel versioninterface Dependencies {
/** Required peer dependency for Babel transpilation */
'@babel/core': '^7.0.0';
/** Required peer dependency for Grunt task execution */
'grunt': '>=0.4.0';
}
interface InternalDependencies {
/** Node.js built-in module for path manipulation */
path: NodeJS.Path;
}interface PlatformSupport {
/** Minimum Node.js version */
nodeVersion: '>=6.9';
/** Windows path separator handling */
windowsSupport: boolean; // Automatically converts backslashes to forward slashes in source maps
}/**
* Grunt instance interface (simplified for babel plugin usage)
*/
interface Grunt {
registerMultiTask(name: string, description: string, taskFunction: Function): void;
file: {
write(filepath: string, contents: string): void;
};
}
/**
* Babel transform result interface
*/
interface BabelTransformResult {
code: string;
map?: SourceMap;
}
/**
* Source map interface
*/
interface SourceMap {
file: string;
sources: string[];
[key: string]: any;
}
/**
* Task context interface (this binding in task function)
*/
interface TaskContext {
async(): () => void;
options(): any;
files: Array<{
src: string[];
dest: string;
}>;
}