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条经验 获得超12个赞
检出使它能够在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)
添加回答
举报