---
title: "AMD：浏览器中的模块规范"
author: "zhouyrt"
date: "2012-03-01T08:07:23Z"
tags: []
categories: ["Web前端"]
slug: "amd"
draft: false
lastmod: "2013-07-26T17:18:47Z"
id: 1431469
url: "https://snandy.iteye.com/blog/1431469"
---

前面提到，为实现与NodeJS相同方式的模块写法，大牛们做了很多努力。

 

但由于浏览器环境不同于服务器端，它的模块有一个HTTP请求过程。这个请求过程多数使用script tag，script tag默认的异步性导致很难实现与NodeJS一模一样的模块格式。

 

[Modules/Wrappings](http://wiki.commonjs.org/wiki/Modules/Wrappings) 使得实现变为现实。虽然和NodeJS的模块写法不完全一致，但也有很多相似之处，使得熟悉NodeJS的程序员有一些亲切感。

 

但NodeJS终究是服务器端的JavaScript，没有必要把这些条条框框放到浏览器JavaScript环境中。这时[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) 诞生了，它的全称为异步模块定义。从名称上看便知它是适合script tag的。也可以说AMD是专门为浏览器中JavaScript环境设计的规范。它吸取了CommonJS的一些优点，但又不照搬它的格式。开始AMD作为CommonJS的[transport format](http://wiki.commonjs.org/wiki/Modules/Transport/C) 存在，因无法与CommonJS开发者达成一致而独立存在。它有独立的[wiki](http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition) 和[讨论组](https://groups.google.com/group/amd-implement) 。

 

AMD设计出一个简洁的写模块API：**define** 。

 

**define(id?, dependencies?, factory);**

 

其中：

- id: 模块标识，可以省略。
- dependencies: 所依赖的模块，可以省略。
- factory: 模块的实现，或者一个JavaScript对象。

id遵循CommonJS [Module Identifiers](http://wiki.commonjs.org/wiki/Modules/1.1.1#Module_Identifiers) 。dependencies元素的顺序和factory参数一一对应。

 

以下是使用AMD模式开发的简单三层结构（基础库/UI层/应用层）：

 

base.js

```
define(function() {
	return {
		mix: function(source, target) {
		}
	};
});
```

 

ui.js

```
define(['base'], function(base) {
	return {
		show: function() {
			// todo with module base
		}
	}
});
```

 

page.js

```
define(['data', 'ui'], function(data, ui) {
	// init here
});
```

 

data.js

```
define({
	users: [],
	members: []
});
```

 

以上也演示了define的三种用法，

**1，定义无依赖的模块** （base.js）

**2，定义有依赖的模块** （ui.js，page.js）

**3，定义数据对象模块** （data.js）

 

 

细心的会发现，还有一种没有出现，即具名模块

 

**4，具名模块**

```
define('index', ['data','base'], function(data, base) {
	// todo
});
```

 

具名模块多数时候是不推荐的，一般打包工具合并多个模块到一个js文件中时会使用。

 

前面提到dependencies元素的顺序和factory一一对应，其实不太严谨。AMD开始为摆脱CommonJS的束缚，开创性的提出了自己的模块风格。但后来又做了妥协，兼容了 CommonJS [Modules/Wrappings](http://wiki.commonjs.org/wiki/Modules/Wrappings) 。即又可以这样写

 

**5，包装模块**

```
define(function(require, exports, module) {
	var base = require('base');
	exports.show = function() {
		// todo with module base
	} 
});
```

 

不考虑多了一层函数外，格式和NodeJS还比较象的。使用require获取依赖模块，使用exports导出API。

 

除了define外，AMD还保留一个关键字require。[**require**](https://github.com/amdjs/amdjs-api/wiki/require) 作为规范保留的全局标识符，可以实现为 module loader。也可以不实现。

 

目前，实现AMD的库有[RequireJS](http://requirejs.org/) 、[curl](https://github.com/unscriptable/curl) 、[Dojo](http://dojotoolkit.org/) 、[bdLoad](http://bdframework.org/bdLoad/) 、[JSLocalnet](http://wiki.commonjs.org/wiki/Implementations/JsDev) 、[Nodules](http://wiki.commonjs.org/wiki/Implementations/Nodules) 等。

也有很多库支持AMD规范，即将自己作为一个模块存在，如[MooTools](http://mootools.net/) 、[jQuery](http://jquery.com/) 、[qwery](https://github.com/ded/qwery) 、[bonzo](https://github.com/ded/bonzo)  甚至还有 [firebug](http://getfirebug.com/) 。

 

 

相关：

[AMD No Longer A CommonJS Specification](http://groups.google.com/group/commonjs/browse_thread/thread/96a0963bcb4ca78f/cf73db49ce267ce1?lnk=gst)

[UMD和ECMAScript模块](/blog/1450665)