JS中的模块化的规范

70 阅读1分钟

包括CommonIS,ES2015,AMD,CMD四个不同的模块规范的比较。

1. CommonJS

一个文件就是一个模块,拥有单独的作用域。普通方式定义的变量,函数,对象都属于该模块。

  • 通过require来加载模块
  • 通过exportsmodul.exports来暴露模块中的内容
// 导出
// hangge.js
exports.hello = function() {
    console.log('hello');
}

// hangge.js
function hello () {
    console.log('hello');
}
module.exports = hello;

// 加载
// main.js
var hangge = require('./hangge');
hangge.hello();

// main.js
var hangge = require('./hangge');
hangge.hello();

2. ES2015 (ES6)

一个模块就是一个独立的文件。该文件内部的所有变量,外部无法获取。

  • export规定模块的对外接口
  • import输入其他模块提供的功能
// 导出: hangge.js
export function fun1 () {
    console.log('fun1');
}
export function fun2 () {
    console.log('fun2');
}
export default function() {
    console.log('default function');
}

// 引入:main.js
import {fun1, fun2} from './hangge'

import * as fun from './hangge'
fun.fun1();
fun.fun2();

//对于默认输出的模块,引用的时候不需要大括号
import func3, {fun1, fun2} from './hangge'

3. AMD(异步模块定义)

是一个浏览器端的模块化开发规范。允许非同步加载模块,也可以按需动态加载模块,requirejs是该规范的实现。

  • define()定义模块
  • require()加载模块
// 定义模块:hangge.js
define('my', ['./a', './b'], function(a, b) {
    return {
        color: 'red',
        addNum: function() {
            console.log(2);
        }
    }
});

// 加载模块: index.html
<script src="require.js"></script>
<script>
require(['my'], function(m) {
    console.log(m.color);
});
</script>

4. CMD

seajs是规范的实现。

  • seajs.use()使用模块接口
  • exportsmodule.exports暴露模块接口
// 定义模块:hangge.js
define(function(require, exports) {
    // 对外提供name属性和hello方法
    exports.name = 'hello';
    exports.hello = function() {
      console.log('hello function');  
    };
});
define(function(require, exports, module) {
    module.exports = {
        name: 'hello',
        hello: function() {
            console.log('hello function.');
        }
    }
});

// 引用模块:index.html
<script src="sea.js"></script>
<script>
seajs.use('hangge', function(m) {
    m.hello();
});
</script>

参考资料:
m.hangge.com/news/cache/…