grunt-contrib-requirejs is a Grunt plugin that optimizes RequireJS projects using the r.js optimizer. It provides a seamless integration between the Grunt task runner and RequireJS build process, enabling developers to compile and optimize AMD (Asynchronous Module Definition) modules into production-ready bundles.
npm install grunt-contrib-requirejs --save-devThis is a Grunt plugin, so it's loaded using Grunt's standard plugin loading mechanism:
// In your Gruntfile.js
grunt.loadNpmTasks('grunt-contrib-requirejs');The plugin exports a single function that registers the 'requirejs' task:
// The main export from tasks/requirejs.js
module.exports = function(grunt) {
// Registers the 'requirejs' multi-task
};// Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
requirejs: {
compile: {
options: {
baseUrl: "js/lib",
mainConfigFile: "js/common.js",
name: "main",
out: "js/main-built.js"
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('build', ['requirejs']);
};The main task for optimizing RequireJS projects using r.js.
/**
* Main plugin function that registers the requirejs task with Grunt
* @param {Object} grunt - Grunt instance
*/
function(grunt) {
grunt.registerMultiTask('requirejs', 'Build a RequireJS project.', function() {
// Task implementation
});
}Usage in Gruntfile.js:
// Basic configuration
requirejs: {
compile: {
options: {
baseUrl: "path/to/base",
name: "main-module",
out: "path/to/optimized.js"
}
}
}
// Multi-target configuration
requirejs: {
dev: {
options: {
baseUrl: "src/js",
name: "main",
out: "dist/js/main-dev.js",
optimize: "none"
}
},
prod: {
options: {
baseUrl: "src/js",
name: "main",
out: "dist/js/main-prod.js",
optimize: "uglify2"
}
}
}Configuration options for the requirejs task. All standard r.js optimizer options are supported, plus additional Grunt-specific options.
interface RequireJSTaskOptions {
// Grunt-specific options
logLevel?: number;
done?: (done: () => void, output: BuildOutput) => void;
error?: (done: () => void, err: Error) => void;
// Standard r.js options (selection of most common)
baseUrl?: string;
mainConfigFile?: string;
name?: string;
include?: string[];
exclude?: string[];
out?: string;
dir?: string;
modules?: ModuleConfig[];
optimize?: string;
preserveLicenseComments?: boolean;
generateSourceMaps?: boolean;
[key: string]: any; // All other r.js options
}
interface BuildOutput {
// r.js build output object (structure depends on r.js version)
[key: string]: any;
}
interface ModuleConfig {
name: string;
include?: string[];
exclude?: string[];
override?: object;
}Grunt-Specific Options:
number): Controls logging verbosity. Uses constants defined in the source:
0 (LOG_LEVEL_TRACE): Verbose logging2 (LOG_LEVEL_WARN): Warnings only (default unless --verbose flag used)Log Level Constants:
const LOG_LEVEL_TRACE = 0;
const LOG_LEVEL_WARN = 2;done (function): Optional callback executed after successful build
done (async callback), output (r.js build output)done() to signal task completionerror (function): Optional error handler for build failures
done (async callback), err (Error object)Example with done callback:
requirejs: {
compile: {
options: {
baseUrl: "js/lib",
name: "main",
out: "js/main-built.js",
done: function(done, output) {
// Analyze build output
var duplicates = require('rjs-build-analysis').duplicates(output);
if (Object.keys(duplicates).length) {
grunt.log.subhead('Duplicates found in requirejs build:');
grunt.log.warn(duplicates);
return done(new Error('r.js built duplicate modules, please check the excludes option.'));
}
done();
}
}
}
}Example with error handler:
requirejs: {
compile: {
options: {
baseUrl: "js/lib",
name: "main",
out: "js/main-built.js",
error: function(done, err) {
grunt.log.warn('RequireJS build failed: ' + err.message);
// Custom error handling logic
done(); // Continue with build process
}
}
}
}All r.js optimizer options are supported. Most commonly used options include:
string): Base URL for module resolutionstring): Path to RequireJS config filestring): Main module name for single-file buildsstring[]): Additional modules to include in buildstring[]): Modules to exclude from buildstring): Output file path for single-file buildsstring): Output directory for multi-file buildsModuleConfig[]): Multi-module build configurationstring): Optimizer to use ('uglify2', 'closure', 'none')boolean): Keep license commentsboolean): Generate source mapsFor complete r.js options documentation, see the r.js example build file.
The plugin provides comprehensive error handling:
grunt.log.errorlns()grunt.fail.warn('RequireJS failed.')done function errors trigger the exact message: grunt.fail.warn('There was an error while processing your done function: "' + e + '"')error function errors trigger the exact message: grunt.fail.fatal('There was an error while processing your error function: "' + e + '"')error callback for custom error processingError Types:
Specific Error Messages:
grunt.log.oklns()All task options support Grunt template variables:
requirejs: {
compile: {
options: {
baseUrl: "<%= meta.srcPath %>",
name: "<%= pkg.name %>",
out: "<%= meta.distPath %>/optimized.js"
}
}
}Configure multiple builds with different settings:
requirejs: {
// Development build
dev: {
options: {
baseUrl: "src",
name: "main",
out: "dist/main-dev.js",
optimize: "none",
preserveLicenseComments: true
}
},
// Production build
prod: {
options: {
baseUrl: "src",
name: "main",
out: "dist/main-prod.js",
optimize: "uglify2",
preserveLicenseComments: false,
generateSourceMaps: true
}
}
}Run specific targets:
grunt requirejs:dev # Development build only
grunt requirejs:prod # Production build only
grunt requirejs # All targets