我非常习惯Lua你能做到这一点,所以如果不可能,请原谅我。
让我们说在client.js上我有2个变量,这两个变量都需要模块
var EmbedManager = require('Embed');
var client = require('Client');
new EmbedManager()
.init()
.output()
来自模块'嵌入'我需要能够访问变量'客户端'没有传递任何东西作为论据。
出于示例的目的,文件存储如下;
Client.js
Embed.js
答案 0 :(得分:1)
如果要从其他模块访问变量,则需要在module.exports
中包含该变量,然后需要该模块。
因此,在Client.js
中,您需要添加一行,如:
// This creates a new exported variable on Client
module.exports.client = client
然后在Embed.js
中,您需要:
// When you import `Client.js`, you're getting whatever
// it `module.exports`
var Client = require("./Client.js")
// So now we can access the `client` variable of the `Client` module
var client = Client.client
找到CommonJS模块格式的良好文档非常棘手,但本文也不错:An Introduction to CommonJS。
答案 1 :(得分:1)
在节点js中,如果您不想传递参数,首先要考虑的是在Client
文件中只需要embed.js
,但这会导致循环依赖性问题。由于client.js
包含embed.js
,反之亦然。
通常,解决这个问题的最佳方法是以一种同时使用client.js
和embed.js
的文件结束重组模块,这样您可能需要创建<thirdFileName>.js
然后同时要求client.js
和embed.js
并在该文件中添加逻辑
thirdFile.js
var EmbedManager = require('Embed');
var client = require('Client');
new EmbedManager().init().output()
new Client().init()
//rest of logic here!
因此要么使用参数,要么构造代码以在一个文件中使用这两个模块