Javascript中定義module的方式有兩種:CommonJS規(guī)范、AMD規(guī)范√溃現(xiàn)將這兩個(gè)詞更全面的定義列一下,以正視聽。
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