【问题标题】:Export/Import Events for diffrent JS Files不同 JS 文件的导出/导入事件
【发布时间】: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 =&gt; { 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 =&gt; 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


【解决方案1】:

您应该只导出客户端:

module.exports = client;

那么只有金额

【讨论】:

  • 我已经试过了,module.exports = client;在我的 index.js 中,但未使用 extern.js 中的代码 sn-p。 const Discord = require("discord.js") var client = require('./index') // log for successfull connected bot client.on("ready", () =&gt; { console.log(`logged in as ${client.user.tag}!`) }) 我如何在我的 extern.js 中准确地要求它
  • var client = require('./index.js') 缺少 .js
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 2018-07-17
  • 2017-03-20
  • 1970-01-01
  • 2017-09-05
  • 2021-10-01
  • 2019-11-27
  • 1970-01-01
相关资源
最近更新 更多