CJS, CommonJS

  • 应用 node server 端
  • 实现 CommonJS
//    filename: foo.js

//    dependencies
var $ = require('jquery');

//    methods
function myFunc(){};

//    exposed public method (single)
module.exports = myFunc;

AMD, Asynchronous Module Definition

  • 浏览器端
  • 实现: RequireJS
//    filename: foo.js
define(['jquery'], function ($) {
    //    methods
    function myFunc(){};

    //    exposed public methods
    return myFunc;
});

UMD,Universal Module Definition

  • CJS 与 AMD 的统一实现。因为你开发的库,可能即支持在 Node 端引入,也支持在浏览器端引入。所以引入一个统一方法。
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS-like
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals (root is window)
        root.returnExports = factory(root.jQuery);
    }
}(this, function ($) {
    //    methods
    function myFunc(){};

    //    exposed public method
    return myFunc;
}));

ES2015

  • ECMAScript 标准
  • 支持服务器端和浏览器端
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

Refs

  1. JavaScript Module Systems Showdown: CommonJS vs AMD vs ES2015
  2. What Is AMD, CommonJS, and UMD?