-
Notifications
You must be signed in to change notification settings - Fork 127
amd
AMD (Asynchronous Module Definition) was the response to those who thought the CommonJS Module system was not ready for the browser because its nature was synchronous.
AMD specifies a standard for modular JavaScript such that modules can load their dependencies asynchronously, solving the problems associated with synchronous loading.
Modules are defined using the define
function.
The define function is how modules are defined with AMD. It is just a function that has this signature
define(id?: String, dependencies?: String[], factory: Function|Object);
Specifies the module name. It is optional.
This argument specifies which module dependencies the module being defined has. It is an array containing module identifiers. It is optional, but if omitted, it defaults to ["require", "exports", "module"].
The last argument is the one who defines the module. It can be a function (which should be called once), or an object. If the factory is a function, the value returned will be the exported value for the module.
Let's see some examples:
Defines a module named myModule
that requires jQuery
.
define('myModule', ['jquery'], function($) {
// $ is the export of the jquery module.
$('body').text('hello world');
});
// and use it
require(['myModule'], function(myModule) {});
Note: In webpack a named module is only locally available. In Require.js a named module is globally available.
Define a module without specifying its id.
define(['jquery'], function($) {
$('body').text('hello world');
});
Define a module with multiple dependencies. Note that each dependency export will be passed to the factory function.
define(['jquery', './math.js'], function($, math) {
// $ and math are the exports of the jquery module.
$('body').text('hello world');
});
Define a module that exports itself.
define(['jquery'], function($) {
var HelloWorldize = function(selector){
$(selector).text('hello world');
};
return HelloWorldize;
});
define(function(require) {
var $ = require('jquery');
$('body').text('hello world');
});
webpack 👍