我非常习惯使用 Lua,您可以做到这一点,所以如果这不可能,请原谅。
假设在 client.js 上我有 2 个变量,这两个变量都需要模块
var EmbedManager = require('Embed');
var client = require('Client');
new EmbedManager()
.init()
.output()
我需要从“嵌入”模块访问变量“客户端”,而无需将任何内容作为参数传递。
为了举例,文件是这样存储的;
Client.js
Embed.js
最佳答案
如果你想从另一个模块访问一个变量,你需要在你的 module.exports
中包含该变量,然后 require 该模块。
因此,在 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 .
关于javascript - 将环境传递给模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342516/