RequireJS
RequireJS is a foundational JavaScript file and module loader, primarily designed for asynchronous module definition (AMD) in web browsers, which was crucial for managing dependencies and organizing code before native ES Modules (ESM) were widely adopted. The `requirejs` npm package provides a Node.js adapter, `r.js`, which serves as both an AMD runtime for server-side execution and a powerful optimizer for bundling and minifying browser-side AMD modules. Its current stable version is 2.3.8, last published in November 2025. While it has received infrequent updates for critical fixes (e.g., a prototype pollution vulnerability fix in 2.3.7), its lead maintainer has indicated it's in "end of life mode" for new feature development. RequireJS differentiates itself by offering a consistent module format across browser and Node environments, simplifying build processes for complex web applications. However, its relevance has significantly diminished with the pervasive support for ES Modules in modern JavaScript ecosystems, which offer more efficient loading and static analysis capabilities without needing a separate loader or optimizer in many scenarios.
Common errors
-
Mismatched anonymous define() modules
cause Multiple `define()` calls without module IDs in a single file or incorrect module loading order in optimized builds.fixEnsure each AMD module file contains only one top-level `define()` call. For optimized builds, consider using the optimizer's naming conventions or ensuring `name` configuration is correct to prevent anonymous modules from clashing. -
Load timeout for modules: [module-name]
cause RequireJS could not load the specified module within the configured `waitSeconds`. Common causes include incorrect paths, server issues (404s), or script errors preventing execution.fixCheck the module's path in your `requirejs.config({ paths: ... })`. Verify the file exists and is accessible. Inspect browser developer tools (Network tab) for 404 errors or console for script errors in the module. Increase `waitSeconds` in `requirejs.config` if the script legitimately takes longer to load (e.g., `waitSeconds: 200`). -
require is not defined
cause This error typically occurs when using Node.js's CommonJS `require()` function in a browser environment without a bundler, or when attempting to use RequireJS's AMD `require()` without the `require.js` script being loaded in the HTML.fixIn browsers, ensure `require.js` is loaded via a `<script>` tag before any AMD modules, and use its `require()` or `define()` for modules. In Node.js, use `const module = require('module');` for CommonJS modules, and the `requirejs` package's configured instance for AMD modules. -
Error evaluating module [module-name]
cause A runtime JavaScript error (e.g., syntax error, uncaught exception) occurred within the `define()` function's factory callback for the specified AMD module.fixInspect your browser's console or Node.js terminal for the full stack trace. The error message should point to the file and line number where the issue originated, indicating a bug within your module's logic.
Warnings
- deprecated The AMD (Asynchronous Module Definition) module format, championed by RequireJS, is largely superseded by native ES Modules (ESM) for new JavaScript projects in both browser and Node.js environments. ESM offers static analysis, tree-shaking, and standardized syntax.
- gotcha When using `requirejs` in Node.js, there's a distinction between Node's native CommonJS `require()` function and RequireJS's AMD `require()` function. Without proper configuration (`nodeRequire`), RequireJS may not correctly resolve modules intended for Node's CommonJS system.
- security RequireJS versions up to 2.3.6 (and 2.3.7 for browser-only usage) were affected by a prototype pollution vulnerability. This could allow attackers to inject arbitrary properties into JavaScript object prototypes.
- gotcha The RequireJS optimizer (`r.js`) does not support building with network paths for modules. All resources must be local files.
- gotcha Using `shim` configuration to manage non-AMD scripts (e.g., older 'browser globals' libraries) is primarily for browser environments. The `shim` config is not fully supported or reliable when running RequireJS in Node.js, and may lead to unexpected behavior or warnings.
Install
-
npm install requirejs -
yarn add requirejs -
pnpm add requirejs
Imports
- requirejs
import requirejs from 'requirejs';
const requirejs = require('requirejs'); - define
const define = require('requirejs').define;// In an AMD module file: define(['dependency'], function(dependency) { /* ... */ }); - require
const require = require('requirejs').require;// In an AMD module file: require(['dependency'], function(dependency) { /* ... */ });
Quickstart
const requirejs = require('requirejs');
const path = require('path');
const fs = require('fs');
// 1. Define sample AMD modules
fs.writeFileSync('dep.js', `define(function() { return { value: 'I am a dependency!' }; });`);
fs.writeFileSync('main.js', `define(['./dep'], function(dep) { return { message: 'Hello from main! Dep says: ' + dep.value }; });`);
// 2. Configure requirejs for Node.js to load AMD modules
requirejs.config({
baseUrl: __dirname, // Current directory as base for AMD modules
nodeRequire: require // Pass Node's require to enable fallback for non-AMD modules
});
// 3. Load an AMD module using the configured requirejs instance
requirejs(['main'], function(mainModule) {
console.log('AMD Module loaded:', mainModule.message);
});
// 4. Using the optimizer programmatically
const buildConfig = {
baseUrl: __dirname,
name: 'main', // The main module to optimize
out: path.join(__dirname, 'main-built.js'), // Output file
optimize: 'none', // For demonstration, keep it unminified
paths: {
dep: './dep' // Ensure optimizer knows about relative paths
}
};
requirejs.optimize(buildConfig, function (buildResponse) {
console.log('\n--- Build Optimization Complete ---');
console.log(buildResponse);
const builtContent = fs.readFileSync(buildConfig.out, 'utf8');
console.log('\nContent of main-built.js (first 500 chars):\n', builtContent.substring(0, 500), '...');
// Clean up generated files
fs.unlinkSync('dep.js');
fs.unlinkSync('main.js');
fs.unlinkSync('main-built.js');
}, function (err) {
console.error('\nRequireJS Optimizer Error:', err);
// Clean up in case of error too
if (fs.existsSync('dep.js')) fs.unlinkSync('dep.js');
if (fs.existsSync('main.js')) fs.unlinkSync('main.js');
if (fs.existsSync('main-built.js')) fs.unlinkSync('main-built.js');
});