Commonjs,AMD,CMD和UMD的差异

 
   

CommonJS

一种服务器端模块化的规范,Nodejs实现了这种规范,所以就说Nodejs支持CommonJS。

CommonJS分为三部分:
require 模块加载
exports 模块导出
module 模块本身

根据规范一个单独的JS文件就是一个module,每个单独的module是一个单独的作用域。也就是说在一个文件里定义的变量和函数都是私有,对其他文件不可见,除非用exports导出了。


AMD

Asynchronous Module Definition 的缩写,意思是异步模块定义,是一种异步模块加载的规范,主要用于浏览器端的JS加载,为了不造成网络阻塞。只有当依赖的模块加载完毕,才会执行回调。

AMD使用define来定义模块,require来加载模块。
define(id?,dependencies?,factory);
require([module],callback);

Note: AMD允许输出的模块兼容CommonJS。

RequireJS是AMD的一种实现。


CMD

Common Module Definition的缩写,也是一种异步模块定义规范,它和AMD的主要区别有两点:
1.对于模块的依赖,AMD是提前执行,CMD是延时执行。
2.AMD推崇依赖前置,CMD推崇就近依赖。

//AMD
define(['./a','./b'], function (a, b) {

    //依赖一开始就写好
    a.test();
    b.test();
});

//CMD
define(function (requie, exports, module) {

    //依赖就近书写
    var a = require('./a');
    a.test();
});

当然还其他区别这里就不详细讲了。

SeaJS是CMD的一种实现。


UMD

Universal Module Definition。从名字就可以看出来UMD做的是大一统的工作,把前后端加载糅合在了一起,提供了一个前后端统一的解决方案。支持AMD和CommonJS模式。

UMD的实现很简单:

1.先判断是否支持Node.js模块格式(exports是否存在),存在则使用Node.js模块格式。
2.再判断是否支持AMD(define是否存在),存在则使用AMD方式加载模块。
3.前两个都不存在,则将模块公开到全局(window或global)。

各种具体的实现方式,可以查看UMD的github。下面是Jquery的例子

扫描二维码关注公众号,回复: 2622600 查看本文章
// if the module has no dependencies, the above pattern can be simplified to
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.returnExports = factory();
  }
}(this, function () {

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};
}));

猜你喜欢

转载自www.cnblogs.com/hanguidong/p/9444382.html