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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文链接:https://auth0.com/blog/javascript-module-systems-sho...
    自度君阅读 944评论 0 2
  • 想你,梦里的一竖二小姐 下过雨的南方的城 洗尽倦意的飘荡的我 不经意的飞过我的世界的你 留下一片喧嚣的风藏在我的安...
    大三在北阅读 251评论 0 0
  • 那是在小学三年级的时候,那会的天空下还没有雾霾,天还是那么蓝,阳光也还是那么暖。那一天傍晚,学校重新分班结束,二我...
    墨莫末阅读 410评论 0 4
  • 2017年07月去广东高校学习交流小文。 今年盛夏去广东省高校交流学习,收获很多。额外惊喜的是在广东几...
    叶生韵阅读 196评论 0 0
  • 狂热的自由 冰冷的静默原来我遇见你的时候除了悸动一无所有
    摄影师柳丁阅读 169评论 0 2