【发布时间】:2022-11-17 09:23:42
【问题描述】:
以下是截取自:https://discordjs.guide/creating-your-bot/command-handling.html#loading-command-files 的 sn-p
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
在 for 循环中,我们通过执行 require(filePath) 来检索命令。如何使用导入实现等效行为?
大多数 Discord.js guide 使用 CommonJS,而我正在尝试使用 TypeScript 实现我的机器人。
【问题讨论】:
-
简短的回答是这很难。也许不可能。在模块中
__dirname是undefined,动态导入是异步的,而 require 是同步的,等等。你可能可以在动态导入数组上使用Promise.all,然后运行命令,但我们需要了解更多关于您的用例的信息。坦率地说,我对 ES 模块的好处持怀疑态度,尤其是对于服务器端代码。 -
@JaredSmith 您可以通过采用
new URL(import.meta.url).pathname并删除文件名来模仿__dirname。 -
@caTS 是的,虽然不得不做
import { dirname } from path; const __dirname = dirname(import.meta.url);或任何只是为了回到旧状态的事情很烦人。 -
您可以使用导入功能并解决承诺
import(path)
标签: typescript discord.js