【问题标题】:How can I share modules between the client and server using node.js if my module depends on another?如果我的模块依赖于另一个模块,如何使用 node.js 在客户端和服务器之间共享模块?
【发布时间】:2012-12-10 16:00:31
【问题描述】:

这是我的 Node.js 情况:

我正在尝试在我的 Node.js 服务器和游戏浏览器之间共享代码。基本上,我想分享游戏逻辑。

假设我的游戏有一个表格,而该表格可以有玩家。我希望每个模块都是客户端和服务器都可以使用的模块。

我知道我可以这样做:

(function(exports){

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

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

我可以在我的表上得到类似的东西。但是,如果我需要在这个 Table 模块中使用 Players 怎么办?比如:

(function(exports){

   exports.test = function(){
        var Player = require('./Player');
        var p1 = new Player();
    };

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

虽然这在 Node 中可以工作,但它显然不能在浏览器上工作,因为没有定义 require。如果没有 require,它可以在浏览器上运行,但不能在 Node 上运行。

TL;DR:我需要将一个模块中的代码“包含”到另一个模块中,这可以由浏览器(客户端)和服务器共享。

谢谢

【问题讨论】:

标签: javascript oop node.js


【解决方案1】:

您可以使用 require.js 在节点和浏览器中加载模块。

See documentation on the require.js page

【讨论】:

  • 这并没有解决如何解决需要一个公共模块,该模块需要依赖于不同的子模块,具体取决于它运行的环境。
猜你喜欢
  • 2014-11-06
  • 2015-12-29
  • 2019-02-15
  • 1970-01-01
  • 2015-10-28
  • 2015-02-27
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
相关资源
最近更新 更多