AMD 定义了一套 JavaScript 模块依赖异步加载标准,来解决同步加载的问题。

使用define函数定义Module.

id

module的名字,可选的.

dependencies 指定了所要依赖的module列表,它是一个数组,也是可选的参数,每个依赖的模块的输出将作为参数一次传入 factory 中。如果没有指定 dependencies,那么它的默认值是 [“require”, “exports”, “module”]。

factory

例子

命名 module

定义一个名为 myModule 的模块,它依赖 jQuery 模块:

  1. define('myModule', ['jquery'], function($) {
  2. // $ is the export of the jquery module.
  3. $('body').text('hello world');
  4. });
  5. // and use it

注意:在 webpack 中,模块名只有局部作用域,在 Require.js 中模块名是全局作用域,可以在全局引用。

多个模块依赖

  1. define(['jquery', './math.js'], function($, math) {
  2. // $ and math are the exports of the jquery module.
  3. $('body').text('hello world');
  4. });

输出模块自身.

在模块定义内部引用依赖

  1. define(function(require) {
  2. var $ = require('jquery');