What is AMD Module key?

What is AMD Module key ?

Hi @vytautokas,

AMD stands for “Asynchronous Module Definitions”. It is a pattern of creating and sharing modules of JavaScript code in a browser. The AMD pattern has a lightweight specification on github.

The AMD pattern exists as an alternative to global JavaScript variables. Here is what the difference looks like between the two approaches:

// creating a "module" in JS globals
window.myAwesomeThing = {
    foo: function () { return "bar"; }
};

// re-using a "module" in JS globals
window.myAwesomeThing.foo();
// creating a module in AMD
define('my-awesome-thing', function() {
    return {
        foo: function() { return "bar"; }
    };
});

// re-using a module in AMD
require(['my-awesome-thing'], function(thing) {
    thing.foo();
});

There are two important advantages in using the AMD approach:

  • Global variables don’t always exist, and it’s hard to determine where a given value comes from. AMD requires that you specify exactly what code your code needs. In AMD, if the modules cannot be found, an error will be thrown and your code won’t be run. This is better than code silently not working at runtime because you forgot to add a script.
  • They are asynchronous. AMD modules can be loaded on to a page lazily, when code that needs them is meant to run.

The AMD pattern was created before ES6 modules were designed or implemented by browsers. Though AMD is not a browser-native pattern, thanks to libraries like require.js, the pattern does have widespread support and works across every old and modern browser alike.

Some AUI components can be consumed by pulling in their AMD module. For instance, if you want to use a flag in AUI, you can get it in one of two ways:

// use AUI flag via global variables
AJS.flag({ body: 'hello there!' });

// use AUI flag via AMD
require(['aui/flag'], function(flag) {
    flag({ body: 'hello there!' });
});

If you configure a library like require.js and tell it where to find the batch files for AUI, the require()-based approach can work even if AUI isn’t included on the page in the initial page load. That can help reduce the time to meaningful first paint in the browser.

Hope that helps,
Daz

4 Likes

You can find a nice historical article written by Addy Osmani about AMD: “Writing Modular JavaScript With AMD, CommonJS & ES Harmony”

1 Like