---
title: "JavaScript在服务器端的模块化"
author: "zhouyrt"
date: "2012-02-28T07:20:46Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2012-04-10T20:53:27Z"
id: 1423630
url: "https://snandy.iteye.com/blog/1423630"
---

服务器端的JSer是幸运的，它有NodeJS，NodeJS遵循了一个称为CommonJS的规范。CommonJS其中就有对写模块的标准化。当然模块化只是其中的一部分而已。具体来说NodeJS实现了

 

- [Modules/1.0](http://wiki.commonjs.org/wiki/Modules/1.0 "Modules/1.0")
- [Promises/B](http://wiki.commonjs.org/wiki/Promises/B "Promises/B")  ([http://github.com/kriskowal/q](http://github.com/kriskowal/q) )
- [Promises/D](http://wiki.commonjs.org/wiki/Promises/D "Promises/D")  ([https://github.com/kriskowal/q](https://github.com/kriskowal/q) )
- [Unit Testing/1.0](http://wiki.commonjs.org/wiki/Unit_Testing/1.0 "Unit Testing/1.0")

模块化方面它实现了Modules/1.0（已经更新到[1.1.1](http://wiki.commonjs.org/wiki/Modules/1.1.1) ）。

以下是node中是写模块的一个示例。

**math.js** 文件

```
exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};
```

increment.js

```
var add = require('math').add;
exports.increment = function(val) {
    return add(val, 1);
};
```

 

**main.js** 文件，该文件为入口文件

```
var inc = require('increment').increment;
var a = 1;
inc(a); // 2
```

 

这就写了一个math、increment、main模块。math提供了add方法来实现数字相加。increment模块依赖于math模块，它提供increment方法实现相加。main获取到increment方法，执行相加操作。

 

我们看到

1，node要求一个js文件对应一个模块。可以把该文件想象成一个匿名函数，所有代码都在匿名函数中，其它模块不可访问除exports外的私有变量。

2，使用exports导出API。

3，使用require加载其它模块。

CommonJS module基本要求如下

1，[标示符](/blog/839359) require，为一个函数，它仅有一个参数为字符串，该字符串须遵守[Module Identifiers](http://wiki.commonjs.org/wiki/Modules/1.0#Module_Identifiers) 的6点规定。

2，require方法返回指定的模块API。

3，如果存在依赖的其它模块，那么依次加载。

4，require不能返回，则抛异常。

5，仅能使用标示符exports导出API。

Modules/1.1较1.0仅增加了标示符module，require函数增加了main和paths属性。而仔细比对1.1与1.1.1后发现除了格式调整了下几乎没有变化。

 

 

相关：

[Modules](http://wiki.commonjs.org/wiki/Modules)

[Modules/1.0](http://wiki.commonjs.org/wiki/Modules/1.0)

[Modules/1.1](http://wiki.commonjs.org/wiki/Modules/1.1)

[Modules/1.1.1](http://wiki.commonjs.org/wiki/Modules/1.1.1)

 

下一篇：[NodeJS模块格式在浏览器中的尝试](/blog/1429884)