標籤: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)