CommonJS規範(轉)

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

 

概述

CommonJS是伺服器端模組的規範,Node.js採用了這個規範。

根據CommonJS規範,一個單獨的檔案就是一個模組。載入模組使用require方法,該方法讀取一個檔案並執行,最後返迴文件內部的exports對象。下面就是一個簡單的模組檔案example.js。

console.log("evaluating example.js");var invisible = function () {  console.log("invisible");}exports.message = "hi";exports.say = function () {  console.log(message);}

使用require方法,載入example.js。

var example = require(‘./example.js‘);

這時,變數example就對應模組中的exports對象,於是就可以通過這個變數,使用模組提供的各個方法。

{  message: "hi",  say: [Function]}

require方法預設讀取js檔案,所以可以省略js尾碼名。

var example = require(‘./example‘);

js檔案名稱前面需要加上路徑,可以是相對路徑(相對於使用require方法的檔案),也可以是絕對路徑。如果省略路徑,node.js會認為,你 要載入一個核心模組,或者已經安裝在本地 node_modules 目錄中的模組。如果載入的是一個目錄,node.js會首先尋找該目錄中的 package.json 檔案,載入該檔案 main 屬性提到的模組,否則就尋找該目錄下的 index.js 檔案。看一個複雜一點的例子。

// foobar.jsfunction foobar(){        this.foo = function(){                console.log(‘Hello foo‘);        }        this.bar = function(){                console.log(‘Hello bar‘);        }} exports.foobar = foobar;

調用該模組的方法如下:

var foobar = require(‘./foobar‘).foobar, test = new foobar(); test.bar(); // ‘Hello bar‘

有時,不需要exports返回一個對象,只需要它返回一個函數。這時,就要寫成module.exports。

module.exports = function () {  console.log("hello world")}

AMD規範與CommonJS規範的相容性

CommonJS規範載入模組是同步的,也就是說,只有載入完成,才能執行後面的操作。AMD規範則是非同步載入模組,允許指定回呼函數。由於 Node.js主要用於伺服器編程,模組檔案一般都已經存在於本地硬碟,所以載入起來比較快,不用考慮非同步載入的方式,所以CommonJS規範比較適 用。但是,如果是瀏覽器環境,要從伺服器端載入模組,這時就必須採用非同步模式,因此瀏覽器端一般採用AMD規範。

AMD規範使用define方法定義模組,下面就是一個例子:

define([‘package/lib‘], function(lib){     function foo(){        lib.log(‘hello world!‘);    }      return {        foo: foo    };});

AMD規範允許輸出的模組相容CommonJS規範,這時define方法需要寫成下面這樣:

define(function (require, exports, module){    var someModule = require("someModule");    var anotherModule = require("anotherModule");        someModule.doTehAwesome();    anotherModule.doMoarAwesome();    exports.asplode = function (){        someModule.doTehAwesome();        anotherModule.doMoarAwesome();    };});

參考連結

Addy Osmani, Writing Modular JavaScript With AMD, CommonJS & ES Harmony

轉載自:http://javascript.ruanyifeng.com/nodejs/commonjs.html#toc0

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.