3 回答

TA貢獻1810條經驗 獲得超4個贊
如果您想編寫一個既可以在客戶端又可以在服務器端使用的模塊,那么我有一篇簡短的博客文章,介紹了一種快速簡便的方法:為Node.js和瀏覽器編寫,實質上是以下內容(this與相同window) :
(function(exports){
// Your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
另外,也有一些旨在在客戶端實現Node.js API的項目,例如Marak的gemini。
您可能還對DNode感興趣,它使您可以公開一個JavaScript函數,以便可以使用基于JSON的簡單網絡協議從另一臺計算機上調用它。

TA貢獻1786條經驗 獲得超13個贊
檢出使它能夠在Node.js模塊模式,AMD模塊模式以及瀏覽器中的全局模式下工作的jQuery源代碼:
(function(window){
var jQuery = 'blah';
if (typeof module === "object" && module && typeof module.exports === "object") {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
}
else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if (typeof define === "function" && define.amd) {
define("jquery", [], function () { return jQuery; });
}
}
})(this)
添加回答
舉報