【发布时间】:2021-05-13 05:23:32
【问题描述】:
我有一个包含所有依赖项和资源的 Index.js,它以这样的方式开始,然后是我的所有函数和事件侦听器
//Index.js
const Discord = require("discord.js")
const external = require("./extern")
const Database = require("@replit/database")
const db = new Database()
const client = new Discord.Client()
//code
module.exports= {client};
现在我想要一个 EventListener,它也在另一个名为 extern.js 的文件中使用 const “客户端”
编辑:
//extern.js
const Discord = require("discord.js")
const client = require('./index')
client.on("ready", () => {
console.log(`logged in as ${client.user.tag}!`)
})
到目前为止我发现了什么:
我创建了一个函数 hello(),它在我的 extern.js 的控制台中打印 hello world 使用“module.exports = hello”导出函数 在我的 index.js 中,我可以使用它
const hello = require ("./extern")
hello()
效果很好,但只要我放了
"const client = require("./index")"
在我的 extern.js 中,即使文件中没有使用“客户端”,我也会收到错误消息,并且该行与函数无关
TypeError: hello is not a function
at Object.<anonymous> (/home/runner/Stechuhr/index.js:184:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/runner/Stechuhr/extern.js:2:14)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
顺便说一句,我在 repl.it 中编码
【问题讨论】:
-
依赖注入,
module.exports = client => { client.on("ready", (... },然后在初始化客户端后在主文件external(client)中,或者从main中抽象出Discord的东西,然后在extern.js中使用它 -
这似乎只是一个通用的导入/导出实现。从一个模块导出
client并将其导入另一个模块,然后您可以在两个文件中使用相同的client对象。 -
要从 require() 中获取返回值,您必须
module.exports一些东西,将 require 视为 in,将 module.exports 视为 out。请参阅一些基本教程或修复replit.com/@lcherone/67496047:如果您需要将某些东西传递给某物的构造函数,那么就像我的上一条评论module.exports = config => new Discord.Client(config)或多module.exports = function(){ return new Discord.Client(...arguments)}或在消费者module.exports = Discord.Client中进行构造,然后在消费者中你可以调用返回new (require('./client'))({foo:'bar'}), in/out
标签: javascript node.js discord.js node-modules