The AMD 1) 2) specifies a mechanism for defining modules such that:
can be specified and loaded asynchronously. 3)
ie Both the module and dependencies can be asynchronously loaded.
The import and export functionality of a module in an AMD specification/environment are split between two functions:
An AMD loader implementation will define them as two global variables require and define
The define function accepts as parameters:
AMD defines a single function define that is available as a free variable or a global variable. 4)
define(
module_id /*optional if not present, the module is anonymous. */,
['my-dependency-1', 'my-dependency-2'], /*optional*/,
function(MyDependency1, MyDependency2) { /*function for instantiating the module or object*/
return function() {};
});
Example 5):
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);
require(['myModule'], function ( myModule ) {
// ...
// AMD module use
myModule.myFunction('Arg1');
// ...
});
This section regroups the module loader implementation based on AMD
requirejs implements and delivers an AMD environment where you can use the define and require function.
Proof:
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
console.log("Is this an AMD environment ? "+(typeof define === 'function' && "amd" in define))
Note the browser alone is not an AMD environment
console.log("Is this an AMD environment ? "+(typeof define === 'function' && "amd" in define))
Because umd is wrapper around amd, you can use any umd module in a AMD environment
AMD supports the notion of packages 7). They are simply collections of modules.
Example with the dojo package configuration 8)
var amdConfig = {
packages: [
{ name: "dojo", location: "//ajax.googleapis.com/ajax/libs/dojo/1.10.4/" },
{ name: "dijit", location: "lib/dijit" },
{ name: "dojox", location: "lib/dojox" }
]
}
A package manager can be used see CommonJS Package Manager.
r.js 9) is a single script that has two major functions:
It is part of the RequireJS project