AMD 定义了一套 JavaScript 模块依赖异步加载标准,来解决同步加载的问题。
使用define
函数定义Module.
id
module的名字,可选的.
dependencies 指定了所要依赖的module列表,它是一个数组,也是可选的参数,每个依赖的模块的输出将作为参数一次传入 factory 中。如果没有指定 dependencies,那么它的默认值是 [“require”, “exports”, “module”]。
factory
例子
命名 module
定义一个名为 myModule 的模块,它依赖 jQuery 模块:
define('myModule', ['jquery'], function($) {
// $ is the export of the jquery module.
$('body').text('hello world');
});
// and use it
注意:在 webpack 中,模块名只有局部作用域,在 Require.js 中模块名是全局作用域,可以在全局引用。
多个模块依赖
define(['jquery', './math.js'], function($, math) {
// $ and math are the exports of the jquery module.
$('body').text('hello world');
});
输出模块自身.
在模块定义内部引用依赖
define(function(require) {
var $ = require('jquery');