0
# AMD Loader
1
2
The RequireJS AMD (Asynchronous Module Definition) loader provides the runtime module loading system for JavaScript applications. It implements the complete AMD specification, enabling modular JavaScript development with automatic dependency resolution and asynchronous loading.
3
4
## Core Functions
5
6
### requirejs()
7
Main module loading function that can be used for both configuration and module loading.
8
9
```javascript { .api }
10
requirejs(deps, callback, errback, optional)
11
```
12
13
**Parameters:**
14
- `deps` (Array|String|Object) - Dependencies array, single module name, or configuration object
15
- `callback` (Function, optional) - Success callback function
16
- `errback` (Function, optional) - Error callback function
17
- `optional` (Object, optional) - Optional configuration parameters
18
19
**Returns:** Context require function or undefined
20
21
**Usage Examples:**
22
23
```javascript
24
// Load modules with dependencies
25
requirejs(['jquery', 'backbone'], function($, Backbone) {
26
// Use loaded modules
27
console.log('jQuery version:', $.fn.jquery);
28
});
29
30
// Load single module
31
requirejs(['app/main'], function(main) {
32
main.init();
33
});
34
35
// Configuration usage
36
requirejs({
37
baseUrl: '/js',
38
paths: {
39
'jquery': 'vendor/jquery-3.6.0'
40
}
41
});
42
```
43
44
### require()
45
Alias for the main requirejs function, providing the same functionality.
46
47
```javascript { .api }
48
require(deps, callback, errback, optional)
49
```
50
51
**Parameters:** Same as `requirejs()`
52
53
**Usage Example:**
54
55
```javascript
56
require(['utils/helper', 'models/user'], function(helper, User) {
57
const user = new User();
58
helper.log('User created');
59
});
60
```
61
62
### define()
63
Defines AMD modules with optional dependencies and exports.
64
65
```javascript { .api }
66
define(name, deps, callback)
67
```
68
69
**Parameters:**
70
- `name` (String, optional) - Module name/ID
71
- `deps` (Array, optional) - Array of dependency module IDs
72
- `callback` (Function|Object) - Module definition function or object
73
74
**Returns:** undefined
75
76
**Usage Examples:**
77
78
```javascript
79
// Named module with dependencies
80
define('myModule', ['jquery', 'underscore'], function($, _) {
81
return {
82
init: function() {
83
console.log('Module initialized');
84
}
85
};
86
});
87
88
// Anonymous module with dependencies
89
define(['dep1', 'dep2'], function(dep1, dep2) {
90
return {
91
// module exports
92
};
93
});
94
95
// Simple object export
96
define({
97
name: 'My Module',
98
version: '1.0'
99
});
100
101
// Function export
102
define(function() {
103
return function(msg) {
104
console.log(msg);
105
};
106
});
107
```
108
109
## Configuration API
110
111
### requirejs.config()
112
Configures the RequireJS loader with various options for module loading behavior.
113
114
```javascript { .api }
115
requirejs.config(config)
116
require.config(config)
117
```
118
119
**Parameters:**
120
- `config` (Object) - Configuration object
121
122
**Configuration Options:**
123
124
```javascript { .api }
125
requirejs.config({
126
// Base URL for module loading
127
baseUrl: '/js',
128
129
// Path mappings for module names
130
paths: {
131
'backbone': 'vendor/backbone-1.4.0',
132
'underscore': 'vendor/underscore-1.13.1',
133
'templates': '../templates'
134
},
135
136
// Shim configuration for non-AMD scripts
137
shim: {
138
'backbone': {
139
deps: ['underscore', 'jquery'],
140
exports: 'Backbone'
141
},
142
'underscore': {
143
exports: '_'
144
}
145
},
146
147
// Module ID mappings
148
map: {
149
'*': {
150
'oldModule': 'newModule'
151
},
152
'some/newmodule': {
153
'foo': 'foo1.2'
154
}
155
},
156
157
// Package configurations
158
packages: [
159
{
160
name: 'myPackage',
161
location: 'vendor/myPackage',
162
main: 'index'
163
}
164
],
165
166
// Module-specific configuration
167
config: {
168
'myModule': {
169
apiKey: 'abc123',
170
debug: true
171
}
172
},
173
174
// Dependencies to load immediately
175
deps: ['app/main'],
176
177
// Callback after deps are loaded
178
callback: function() {
179
console.log('All dependencies loaded');
180
},
181
182
// Enforce define() usage
183
enforceDefine: false,
184
185
// Create script tags for XHTML
186
xhtml: false,
187
188
// Query string arguments for URLs
189
urlArgs: 'v=' + Date.now(),
190
191
// Script tag type attribute
192
scriptType: 'text/javascript',
193
194
// Skip data-main attribute processing
195
skipDataMain: false
196
});
197
```
198
199
## Properties and Utilities
200
201
### requirejs.version
202
RequireJS version string.
203
204
```javascript { .api }
205
console.log(requirejs.version); // "2.3.7"
206
```
207
208
### requirejs.jsExtRegExp
209
Regular expression for detecting JavaScript file extensions.
210
211
```javascript { .api }
212
const jsRegex = requirejs.jsExtRegExp;
213
console.log(jsRegex.test('module.js')); // true
214
```
215
216
### requirejs.isBrowser
217
Boolean indicating if running in browser environment.
218
219
```javascript { .api }
220
if (requirejs.isBrowser) {
221
// Browser-specific code
222
}
223
```
224
225
### requirejs.nextTick()
226
Execute function on next event loop tick.
227
228
```javascript { .api }
229
requirejs.nextTick(fn)
230
```
231
232
**Parameters:**
233
- `fn` (Function) - Function to execute
234
235
**Usage:**
236
237
```javascript
238
requirejs.nextTick(function() {
239
console.log('Executed on next tick');
240
});
241
```
242
243
### requirejs.onError()
244
Default error handler for require errors. Can be overridden for custom error handling.
245
246
```javascript { .api }
247
requirejs.onError = function(err) {
248
console.error('RequireJS Error:', err.requireType);
249
console.error('Modules:', err.requireModules);
250
throw err;
251
};
252
```
253
254
**Error Properties:**
255
- `err.requireType` - Error category
256
- `err.requireModules` - Array of module IDs involved in error
257
258
### requirejs.createNode()
259
Create script DOM element for module loading (browser environments).
260
261
```javascript { .api }
262
requirejs.createNode(config, moduleName, url)
263
```
264
265
**Parameters:**
266
- `config` (Object) - RequireJS configuration
267
- `moduleName` (String) - Name of module being loaded
268
- `url` (String) - URL of script to load
269
270
**Returns:** DOM script element
271
272
### requirejs.load()
273
Load a module script.
274
275
```javascript { .api }
276
requirejs.load(context, moduleName, url)
277
```
278
279
**Parameters:**
280
- `context` (Object) - RequireJS context
281
- `moduleName` (String) - Module name
282
- `url` (String) - Script URL
283
284
### requirejs.exec()
285
Execute JavaScript code (used by transpiling plugins).
286
287
```javascript { .api }
288
requirejs.exec(text)
289
```
290
291
**Parameters:**
292
- `text` (String) - JavaScript code to execute
293
294
**Returns:** Execution result
295
296
**Usage:**
297
298
```javascript
299
requirejs.exec('console.log("Hello from executed code");');
300
```
301
302
### requirejs.toUrl()
303
Convert a module name to a URL path for resource loading.
304
305
```javascript { .api }
306
requirejs.toUrl(moduleNamePlusExt)
307
```
308
309
**Parameters:**
310
- `moduleNamePlusExt` (String) - Module name with file extension
311
312
**Returns:** String - Full URL path to the resource
313
314
**Usage:**
315
316
```javascript
317
// Get URL for a text file
318
const templateUrl = require.toUrl('templates/header.html');
319
320
// Get URL for a CSS file
321
const styleUrl = require.toUrl('styles/main.css');
322
323
// Used commonly in plugins
324
define({
325
load: function(name, req, onload, config) {
326
const url = req.toUrl(name + '.txt');
327
// Load resource from url...
328
}
329
});
330
```
331
332
### requirejs.undef()
333
Undefine a module, removing it from the registry and allowing it to be reloaded.
334
335
```javascript { .api }
336
requirejs.undef(moduleName)
337
```
338
339
**Parameters:**
340
- `moduleName` (String) - Name of module to undefine
341
342
**Usage:**
343
344
```javascript
345
// Undefine a module so it can be reloaded
346
requirejs.undef('app/config');
347
348
// Reload the module
349
require(['app/config'], function(config) {
350
// Uses fresh copy of the module
351
});
352
```
353
354
## Special Dependencies
355
356
RequireJS provides several special dependency strings for accessing module metadata and functionality:
357
358
### require
359
Local require function for loading modules relative to the current module.
360
361
```javascript
362
define(['require'], function(require) {
363
// Dynamically load modules
364
require(['./localModule'], function(localMod) {
365
// Use locally loaded module
366
});
367
});
368
```
369
370
### exports
371
Object for exporting module values (CommonJS-style).
372
373
```javascript { .api }
374
define(['exports'], function(exports) {
375
exports.myFunction = function() {
376
return 'Hello World';
377
};
378
});
379
```
380
381
### module
382
Module metadata object containing module information.
383
384
```javascript { .api }
385
define(['module'], function(module) {
386
console.log('Module ID:', module.id);
387
console.log('Module URI:', module.uri);
388
console.log('Module config:', module.config());
389
});
390
```
391
392
## Context Management
393
394
### Multiple Contexts
395
RequireJS supports multiple independent contexts for isolating module namespaces.
396
397
```javascript { .api }
398
// Create custom context
399
const myContext = requirejs.config({
400
context: 'myApp',
401
baseUrl: '/js/myapp'
402
});
403
404
// Use context-specific require
405
myContext(['module1'], function(mod1) {
406
// Module loaded in myApp context
407
});
408
```
409
410
### Context Methods
411
412
```javascript { .api }
413
// Get require function for context
414
const contextRequire = requirejs.config({
415
context: 'myContext'
416
});
417
418
// Check if module is defined
419
contextRequire.defined('moduleName');
420
421
// Get module if defined
422
contextRequire.specified('moduleName');
423
```
424
425
## AMD Feature Detection
426
427
### define.amd
428
AMD feature detection property indicating AMD support.
429
430
```javascript { .api }
431
if (typeof define === 'function' && define.amd) {
432
// AMD environment detected
433
define(['jquery'], function($) {
434
// AMD module definition
435
});
436
} else {
437
// Non-AMD environment
438
}
439
```
440
441
The `define.amd` object contains:
442
```javascript { .api }
443
define.amd = {
444
jQuery: true // Indicates jQuery compatibility
445
};
446
```
447
448
## Error Handling
449
450
### Error Types
451
RequireJS categorizes errors by type via the `requireType` property:
452
453
- `'timeout'` - Module failed to load within timeout
454
- `'nodefine'` - Script did not call define()
455
- `'scripterror'` - Script loading error
456
- `'mismatch'` - Module name mismatch
457
458
### Custom Error Handling
459
460
```javascript
461
require(['nonexistent'],
462
function() {
463
// Success callback
464
},
465
function(err) {
466
console.error('Failed to load:', err.requireModules);
467
console.error('Error type:', err.requireType);
468
}
469
);
470
```
471
472
## Advanced Usage
473
474
### Dynamic Module Loading
475
476
```javascript
477
define(['require'], function(require) {
478
function loadUserModule(userId) {
479
const modulePath = 'users/' + userId;
480
require([modulePath], function(userModule) {
481
// Use dynamically loaded module
482
});
483
}
484
485
return { loadUserModule };
486
});
487
```
488
489
### Conditional Loading
490
491
```javascript { .api }
492
define(['require'], function(require) {
493
if (typeof window !== 'undefined') {
494
// Browser environment
495
require(['dom/utils'], function(domUtils) {
496
// Use DOM utilities
497
});
498
} else {
499
// Node.js environment
500
require(['node/utils'], function(nodeUtils) {
501
// Use Node utilities
502
});
503
}
504
});
505
```