CommonJS vs. AMD

Javascript中定义module的方式有两种:CommonJS规范、AMD规范。现将这两个词更全面的定义列一下,以正视听。

CommonJS

CommonJS is a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.

示例
// mylib.js
// package/lib is a dependency we require
var lib = require( "package/lib" );

// behavior for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules as foobar
exports.foobar = foo;
使用
//  main.js (与mylib.js在相同目录)
var my = require('./mylib');
my.foobar();

AMD

AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side.

It is unrelated to the technology company AMD and the processors it makes.

示例
// mylib.js
// package/lib is a dependency we require
define(["package/lib"], function (lib) {

    // behavior for our module
    function foo() {
        lib.log( "hello world!" );
    }

    // export (expose) foo to other modules as foobar
    return {
        foobar: foo
    }
});
使用

同步方式(同上)

//  main.js (与mylib.js在相同目录)
var my = require('./mylib');
my.foobar();

异步方式

//  main.js (与mylib.js在相同目录)
require(['./mylib'], function(my) {
    my.foobar();
});

参考

Thanks to stackoverflow

你可能感兴趣的:(CommonJS vs. AMD)