英文:
Problem with converting code to ES6 Discord.js
问题
我有旧的Discord机器人代码,我正在尝试将其改写为ES6。以下是代码:
const commandFiles = fs.readdirSync('./commandsBackend/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commandsBackend/${file}`);
client.commands.set(command.name, command);
}
if (interaction.commandName === 'ping' || interaction.commandName === 'p') {
client.commands.get('ping').execute(message, args, db);
};
我在这一行遇到问题:
const command = require(`./commandsBackend/${file}`);
我尝试将其转换为:
import command from `./commandsBackend/${file}` 或 import {command} from `./commandsBackend/${file}`
但这不起作用。我遇到以下错误:
file:///home/runner/VeriusBot/index.js:33
import command from `./commandsBackend/${file}`;
^^^^^^^
SyntaxError: Unexpected identifier
我希望将其转换为可正常工作的形式,而不想在文件顶部为所有命令编写所有导入语句。有人可以帮忙吗?
英文:
I have old code for discord bot and i'm trying to write this in ES6. Here is code:
const commandFiles = fs.readdirSync('./commandsBackend/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commandsBackend/${file}`);
client.commands.set(command.name, command);
}
if (interaction.commandName === 'ping' || interaction.commandName === 'p') {
client.commands.get('ping').execute(message, args, db);
};
I have problem with this line
const command = require(`./commandsBackend/${file}`);
I tried to convert this to:
import command from `./commandsBackend/${file}` or import {command} from `./commandsBackend/${file}`
but this isn't working.
I have this error:
file:///home/runner/VeriusBot/index.js:33
import command from `./commandsBackend/${file}`;
^^^^^^^
SyntaxError: Unexpected identifier
I want to convert this that this will be working, i don't want to write all imports for all commands on top of file. Can someone help?
答案1
得分: 2
在考虑此代码应该在一个async
函数内部的情况下,您可以这样做:
const commandFiles = fs.readdirSync('./commandsBackend/').filter((file) => file.endsWith('.js'))
for (const file of commandFiles) {
const command = await import(`./commandsBackend/${file}`)
client.commands.set(command.name, command)
}
if (['ping', 'p'].includes(interaction.commandName)) {
client.commands.get('ping').execute(message, args, db)
}
英文:
Considering that this code should be within an async
function, you can do:
const commandFiles = fs.readdirSync('./commandsBackend/').filter((file) => file.endsWith('.js'))
for (const file of commandFiles) {
const command = await import(`./commandsBackend/${file}`)
client.commands.set(command.name, command)
}
if (['ping', 'p'].includes(interaction.commandName)) {
client.commands.get('ping').execute(message, args, db)
}
答案2
得分: 0
在你的 package.json 文件中,将 "type"
更改为: "type": "module"
。
英文:
Inside your package.json file, change "type"
to: "type": "module"
{
// ^^^
"type": "module",
// VVV
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论