这是我的 Node.js 情况:
我正在尝试在 Node.js 服务器和游戏浏览器之间共享代码。基本上我想分享一下游戏逻辑。
假设我的游戏有一个 table ,并且该 table 可以有玩家。我希望每个模块都是客户端和服务器都可以使用的模块。
我知道我可以做这样的事情:
(function(exports){
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['Table']={}: exports);
我可以在我的 table 上得到类似的东西。但是,如果我需要在这个 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:我需要将一个模块中的代码“包含”到另一个模块中,该模块可以由浏览器(客户端)和服务器共享。
谢谢
最佳答案
您可以使用 require.js 在 Node 和浏览器中加载模块。
关于javascript - 如果我的模块依赖于另一个模块,如何使用 node.js 在客户端和服务器之间共享模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804508/