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?
CodePudding user response:
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)
}
CodePudding user response:
Inside your package.json file, change "type"
to: "type": "module"
{
// ^^^
"type": "module",
// VVV
}