As a JavaScript application grows, one large codebase becomes harder to maintain, and globals become more likely to clash. AMD is a module specification designed for browsers: it lets you group related code, expose a public interface, and declare dependencies without blocking while those dependencies load. section 11.0 section 11.1.2
Defining an AMD module has three parts:
- Give the module an ID that other modules can use to request it. section 11.1.2
- List the IDs of its dependencies. AMD requests them asynchronously. section 11.1.2
- Supply a factory function. Once the dependencies are downloaded and evaluated, AMD passes them to the factory as arguments; the returned object can expose the public interface. section 11.1.2
Listing 11.3. Using AMD to specify a module dependent on jQuery
define('MouseCounterModule',['jQuery'], $ => { #A
let numClicks = 0;
const handleClick = () => {
alert(++numClicks);
};
return { #B
countClicks: () => {
$(document).on("click", handleClick);
}
};
});
The click-counter module declares jQuery as a dependency. Its factory keeps the click count private and returns a countClicks method as the public interface. section 11.1.2
AMD and CommonJS solve similar modularization problems but make different loading choices. AMD targets browser constraints with asynchronous dependency loading; CommonJS loads modules synchronously and is more suited to server-side JavaScript. ES6 modules later combined a simpler syntax influenced by CommonJS with asynchronous loading as in AMD. section 11.1.2 section 11.3
