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.
define
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);
id
Specifies the module name. It is optional.
dependencies
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"].
factory
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
define(['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;
});
Using require to load dependencies
define(function(require) {
var $ = require('jquery');
$('body').text('hello world');
});