如何在Node.js和浏览器之间共享代码? [英] How can I share code between Node.js and the browser?

查看:152
本文介绍了如何在Node.js和浏览器之间共享代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript客户端(在浏览器中运行)和Node.js服务器创建一个小应用程序,使用WebSocket进行通信。

I am creating a small application with a JavaScript client (run in the browser) and a Node.js server, communicating using WebSocket.

我想分享客户端和服务器之间的代码。我刚刚开始使用Node.js,至少可以说,我对现代JavaScript的了解有点生疏。所以我仍然围绕CommonJS的require()函数。如果我使用'export'对象创建我的包,那么我无法看到如何在浏览器中使用相同的JavaScript文件。

I would like to share code between the client and the server. I have only just started with Node.js and my knowledge of modern JavaScript is a little rusty, to say the least. So I am still getting my head around the CommonJS require() function. If I am creating my packages by using the 'export' object, then I cannot see how I could use the same JavaScript files in the browser.

我想创建一个两端使用的一组方法和类,以便于编码和解码消息,以及其他镜像任务。但是,Node.js / CommonJS打包系统似乎阻止我创建可以在双方使用的JavaScript文件。

I want to create a set of methods and classes that are used on both ends to facilitate encoding and decoding messages, and other mirrored tasks. However, the Node.js/CommonJS packaging systems seems to preclude me from creating JavaScript files that can be used on both sides.

我也尝试使用JS.Class来获取一个更严格的OO模型,但我放弃了,因为我无法弄清楚如何让提供的JavaScript文件与require()一起使用。我在这里找不到什么东西?

I also tried using JS.Class to get a tighter OO model, but I gave up because I couldn't figure out how to get the provided JavaScript files to work with require(). Is there something am I missing here?

推荐答案

如果你想编写一个可以同时用于客户端和服务器端的模块,我有一个简短的博客文章,快速简便的方法: 为Node.js和浏览器编写 ,基本上如下(其中窗口相同):

If you want to write a module that can be used both client side and server side, I have a short blog post on a quick and easy method: Writing for Node.js and the browser, essentially the following (where this is the same as window):

(function(exports){

    // Your code goes here

   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);

或者,有一些项目旨在在客户端实现Node.js API,例如< a href =https://github.com/marak/gemini.js =noreferrer> Marak的双子座。

Alternatively there are some projects aiming to implement the Node.js API on the client side, such as Marak's gemini.

你可能也是对 DNode 感兴趣,它允许您公开JavaScript函数,以便可以使用简单的方法从其他计算机调用它基于JSON的网络协议。

You might also be interested in DNode, which lets you expose a JavaScript function so that it can be called from another machine using a simple JSON-based network protocol.

这篇关于如何在Node.js和浏览器之间共享代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆