我正在用JavaScript客户端(在浏览器中运行)和Node.js服务器创建一个小应用程序,使用WebSocket通信。
我想在客户机和服务器之间共享代码。我才刚刚开始使用Node.js,至少可以说,我对现代JavaScript的知识有点生疏。因此,我仍然对CommonJS的require()函数感到困惑。如果我通过使用“export”对象创建我的包,那么我无法看到我如何在浏览器中使用相同的JavaScript文件。
我想创建一组在两端使用的方法和类,以方便编码和解码消息以及其他镜像任务。然而,Node.js/CommonJS打包系统似乎阻止了我创建可以在双方使用的JavaScript文件。
我还尝试使用JS.Class来获得更紧密的OO模型,但我放弃了,因为我不知道如何让提供的JavaScript文件与require()一起工作。我是不是遗漏了什么?
如果你想写一个既可以在客户端也可以在服务器端使用的模块,我有一个简短的博客文章,关于一个快速而简单的方法:为Node.js和浏览器编写,基本上如下(这与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的网络协议从另一台机器调用它。
用例:在Node.js和浏览器之间共享你的应用配置(这只是一个例子,可能不是最好的方法,这取决于你的应用)。
问题:你不能使用window(在Node.js中不存在)或global(在浏览器中不存在)。
编辑:现在我们可以感谢globalThis和Node.js >= 12。
过时的解决方案:
文件config.js:
Var config = {
喷火:“酒吧”
};
If (typeof module === 'object')模块。导出= config;
在浏览器(index.html)中:
< script src = " config.js " > < /脚本>
< script src = " myApp.js " > < /脚本>
现在可以打开开发工具并访问全局变量配置
在Node.js (app.js)中:
Const config = require('./config');
console.log (config.foo);//打印'bar'
使用Babel或TypeScript:
从'./config'导入配置;
console.log (config.foo);//打印'bar'
在浏览器的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)