相容 CommonJS 和 CommonJS-like規範(1~38)

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

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

根據CommonJS規範,一個單獨的檔案就是一個模組。每一個模組都是一個單獨的範圍,也就是說,在該模組內部定義的變數,無法被其他模組讀取,除非定義為global對象的屬性。

如果jquery要在node中使用,要解決兩個問題:

1.以module.exports的方式匯入(CommonJS模組引入)

2.因為是伺服器環境,是沒有window變數的。

/*! * jQuery JavaScript Library v2.1.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:11Z */(function( global, factory ) {    if ( typeof module === "object" && typeof module.exports === "object" ) {        // For CommonJS and CommonJS-like environments where a proper window is present,        // execute the factory and get jQuery        // For environments that do not inherently posses a window with a document        // (such as Node.js), expose a jQuery-making factory as module.exports        // This accentuates the need for the creation of a real window        // e.g. var jQuery = require("jquery")(window);        // See ticket #14549 for more info        module.exports = global.document ?            factory( global, true ) :            function( w ) {if ( !w.document ) {                    throw new Error( "jQuery requires a window with a document" );                }                return factory( w );            };    } else {        factory( global );    }// Pass this if window is not defined yet}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {    //factory code....}))

根據代碼,jquery採用一個立即調用函數,判斷是否是CommonJS規範(typeof module === "object" && typeof module.exports === "object"),不是則調用庫函數,是則再判斷有沒有document(走到這步是判斷過沒有window,開啟沒有window模式),有則調用庫函數,

無則返回一個等待傳入window的匿名函數。

相容 CommonJS 和 CommonJS-like規範(1~38)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.