liveBook · Manning

AMD

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript module format designed to support asynchronous module loading and dependency resolution, especially in browsers.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains define’s ID, dependency list, and factory through a worked module; defers project setup.
Examples
Uses a jQuery-dependent click-counter module whose returned object exposes a method while retaining a private count.
What it assumes
Assumes familiarity with JavaScript functions and objects, building on closures and the module pattern.
What you can do after
Build it from scratch using define to declare dependencies and return a module’s public interface.
How it connects
Connects AMD to the module pattern, CommonJS, ES6 modules, closures, and asynchronous loading.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.