---
title: "UMD和ECMAScript模块"
author: "zhouyrt"
date: "2012-03-19T15:57:59Z"
tags: []
categories: ["Web前端"]
slug: "umd-ecmascript"
draft: false
lastmod: "2012-03-20T13:15:16Z"
id: 1450665
url: "https://snandy.iteye.com/blog/1450665"
---

**一、UMD：AMD 和CommonJS的糅合**

 

前面花了很长的篇幅介绍了两大类模块规范，CommonJS([Modules](http://wiki.commonjs.org/wiki/Modules/1.1.1)/[Modules/Wrappings](http://wiki.commonjs.org/wiki/Modules/Wrappings))及[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)。

 

我们知道Modules/Wrappings是出于对NodeJS模块格式的偏好而包装下使其在浏览器中得以实现。

 

而Modules/Wrappings的格式通过某些工具（如[r.js](https://github.com/jrburke/r.js)）也能运行在NodeJS中。事实上，这两种格式同时有效且都被广泛使用。

 

AMD以浏览器为第一（browser-first）的原则发展，选择异步加载模块。它的模块支持对象（objects）、函数（functions）、构造器（constructors）、字符串（strings）、JSON等各种类型的模块。因此在浏览器中它非常灵活。

 

CommonJS module以服务器端为第一（server-first）的原则发展，选择同步加载模块。它的模块是无需包装的（unwrapped modules）且贴近于ES.next/Harmony的模块格式。但它仅支持对象类型（objects）模块。

 

 

这迫使一些人又想出另一个更通用格式 [UMD](https://github.com/umdjs/umd)(Universal Module Definition)。希望提供一个前后端跨平台的解决方案。

 

UMD的实现很简单，先判断是否支持NodeJS模块格式（exports是否存在），存在则使用NodeJS模块格式。

再判断是否支持AMD（define是否存在），存在则使用AMD方式加载模块。前两个都不存在，则将模块公开的全局（window或global）。

 

下面是一个示例

 

eventUtil.js

```
(function (root, factory) {
	if (typeof exports === 'object') {
		module.exports = factory();
		
	} else if (typeof define === 'function' && define.amd) {
		define(factory);
		
	} else {
		root.eventUtil = factory();
	}
})(this, function() {
	// module
	return {
		addEvent: function(el, type, handle) {
			//...
		},
		removeEvent: function(el, type, handle) {
			
		},
	};
});
```

 

虽然UMD八字还没有一撇，有些开源库却开始支持UMD了， 如大名鼎鼎的《JavaScript设计模式》作者[Dustin Diaz](http://dustindiaz.com/)开发的[qwery](https://github.com/ded/qwery)。 代码如下

![](http://dl.iteye.com/upload/attachment/0064/6723/1b162f1d-38aa-34cf-b85f-217dae2b81b9.png)

 

 

 

**二、ECMAScript：未来的JS模块化**

 

ECMAScript的下一个版本[Harmony](http://blog.mozilla.com/dherman/2011/02/23/my-js-meetup-talk/)已经考虑到了模块化的需求。

 

使用module关键字来定义一个模块

```
module math {
    export function sum(x, y) {
        return x + y;
    }
    export var pi = 3.141593;
}
```

 

使用import关键字来加载外部模块

```
// we can import in script code, not just inside a module
import {sum, pi} from math;
alert("2π = " + sum(pi, pi));
```

 

引入所有API

```
// import everything
import * from math;
alert("2π = " + sum(pi, pi));
```

 

使用另一个引用作为别名

```
// a static module reference
module M = math;
 
// reify M as an immutable "module instance object"
alert("2π = " + M.sum(M.pi, M.pi));
```

 

 

局部重命名

```
import { draw: drawShape } from shape;
import { draw: drawGun } from cowboy;
```

 

嵌套模块

```
module widgets {
    export module button { ... }
    export module alert { ... }
    export module textarea { ... }
    ...
}
 
import { messageBox, confirmDialog } from widgets.alert;
...
```

 

从服务器上请求的模块

```
<script type=”harmony”>
// loading from a URL
module JSON at 'http://json.org/modules/json2.js';
 
alert(JSON.stringify({'hi': 'world'}));
```

 

动态载入一个模块

```
Loader.load('http://json.org/modules/json2.js', function(JSON) {
	alert(JSON.stringify([0, {a: true}]));
});
```

 

ES modules还需要很长时间来规范化。且它有个问题，即新的语法关键字不能向下兼容（如低版本IE浏览器）。

 

 

相关：

[harmony:modules](http://wiki.ecmascript.org/doku.php?id=harmony%3Amodules)

[harmony:module\_loaders](http://wiki.ecmascript.org/doku.php?id=harmony%3Amodule_loaders)