{"id":11941,"library":"requirejs","title":"RequireJS","description":"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.","status":"maintenance","version":"2.3.8","language":"javascript","source_language":"en","source_url":"https://github.com/jrburke/r.js","tags":["javascript"],"install":[{"cmd":"npm install requirejs","lang":"bash","label":"npm"},{"cmd":"yarn add requirejs","lang":"bash","label":"yarn"},{"cmd":"pnpm add requirejs","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the CommonJS entry point for the Node.js adapter, providing access to the RequireJS configuration and optimizer. Direct ES Module `import` syntax is not typically supported without a CommonJS wrapper or bundler.","wrong":"import requirejs from 'requirejs';","symbol":"requirejs","correct":"const requirejs = require('requirejs');"},{"note":"`define` is a global function made available by the RequireJS runtime (e.g., when `require.js` or `r.js` is loaded) for defining Asynchronous Module Definition (AMD) modules. It is not directly imported from the `requirejs` npm package but is part of the environment it creates.","wrong":"const define = require('requirejs').define;","symbol":"define","correct":"// In an AMD module file:\ndefine(['dependency'], function(dependency) { /* ... */ });"},{"note":"The `require` function in the context of RequireJS is used to load AMD modules asynchronously. It is a global function provided by the RequireJS runtime, distinct from Node.js's native CommonJS `require` function. When using the `requirejs` Node adapter, you can also use `requirejs(['module-id'], callback)` after configuration.","wrong":"const require = require('requirejs').require;","symbol":"require","correct":"// In an AMD module file:\nrequire(['dependency'], function(dependency) { /* ... */ });"}],"quickstart":{"code":"const requirejs = require('requirejs');\nconst path = require('path');\nconst fs = require('fs');\n\n// 1. Define sample AMD modules\nfs.writeFileSync('dep.js', `define(function() { return { value: 'I am a dependency!' }; });`);\nfs.writeFileSync('main.js', `define(['./dep'], function(dep) { return { message: 'Hello from main! Dep says: ' + dep.value }; });`);\n\n// 2. Configure requirejs for Node.js to load AMD modules\nrequirejs.config({\n  baseUrl: __dirname, // Current directory as base for AMD modules\n  nodeRequire: require // Pass Node's require to enable fallback for non-AMD modules\n});\n\n// 3. Load an AMD module using the configured requirejs instance\nrequirejs(['main'], function(mainModule) {\n  console.log('AMD Module loaded:', mainModule.message);\n});\n\n// 4. Using the optimizer programmatically\nconst buildConfig = {\n  baseUrl: __dirname,\n  name: 'main', // The main module to optimize\n  out: path.join(__dirname, 'main-built.js'), // Output file\n  optimize: 'none', // For demonstration, keep it unminified\n  paths: {\n    dep: './dep' // Ensure optimizer knows about relative paths\n  }\n};\n\nrequirejs.optimize(buildConfig, function (buildResponse) {\n  console.log('\\n--- Build Optimization Complete ---');\n  console.log(buildResponse);\n  const builtContent = fs.readFileSync(buildConfig.out, 'utf8');\n  console.log('\\nContent of main-built.js (first 500 chars):\\n', builtContent.substring(0, 500), '...');\n\n  // Clean up generated files\n  fs.unlinkSync('dep.js');\n  fs.unlinkSync('main.js');\n  fs.unlinkSync('main-built.js');\n\n}, function (err) {\n  console.error('\\nRequireJS Optimizer Error:', err);\n  // Clean up in case of error too\n  if (fs.existsSync('dep.js')) fs.unlinkSync('dep.js');\n  if (fs.existsSync('main.js')) fs.unlinkSync('main.js');\n  if (fs.existsSync('main-built.js')) fs.unlinkSync('main-built.js');\n});","lang":"javascript","description":"This quickstart demonstrates how to use the `requirejs` npm package in Node.js to load a simple AMD module and programmatically run the `r.js` optimizer to bundle modules."},"warnings":[{"fix":"For new projects, consider using native ES Modules (`import`/`export`) or CommonJS (`require`/`module.exports`) depending on your target environment and existing codebase. Modern bundlers like Webpack, Rollup, or Vite can handle ESM efficiently.","message":"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.","severity":"deprecated","affected_versions":">=2.0"},{"fix":"When initializing RequireJS in Node, pass Node's `require` function to the `nodeRequire` configuration option: `requirejs.config({ nodeRequire: require });` This allows RequireJS to fall back to Node's module loader if an AMD module is not found.","message":"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.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"Upgrade to RequireJS version 2.3.8 or later to mitigate the prototype pollution vulnerability. If an upgrade is not immediately possible, apply a global shim to prevent prototype pollution.","message":"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.","severity":"security","affected_versions":"<2.3.8"},{"fix":"Ensure all module paths in your build configuration are relative to the `baseUrl` or `mainConfigFile` and point to local files. If you have external dependencies, configure them as module names and map them to local files or use a different build strategy for those parts.","message":"The RequireJS optimizer (`r.js`) does not support building with network paths for modules. All resources must be local files.","severity":"gotcha","affected_versions":">=0.4.0"},{"fix":"Avoid using `shim` configuration when running RequireJS within a Node.js environment. If you need to include non-AMD libraries, consider using a separate CommonJS-compatible version if available, or isolate their usage to the browser build. RequireJS will log a warning about `shim` config in Node, which can be suppressed with `requirejs.config({ suppress: { nodeShim: true }});`.","message":"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.","severity":"gotcha","affected_versions":">=2.1.7"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure 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.","cause":"Multiple `define()` calls without module IDs in a single file or incorrect module loading order in optimized builds.","error":"Mismatched anonymous define() modules"},{"fix":"Check 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`).","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.","error":"Load timeout for modules: [module-name]"},{"fix":"In 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.","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.","error":"require is not defined"},{"fix":"Inspect 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.","cause":"A runtime JavaScript error (e.g., syntax error, uncaught exception) occurred within the `define()` function's factory callback for the specified AMD module.","error":"Error evaluating module [module-name]"}],"ecosystem":"npm"}