I'm converting my bot on an ES6 syntax. Since I can't use: const command = require(`./commands/${file}`)
, I tried with import command from `./commands/${file}`;
. It didn't work, and it gave me a weird error:
file:///D:/Documenti/Coding/Discord/XayBot/XayBotMain/src/index.js:15
import command from `./commands/${file}`;
^^^^^^^
SyntaxError: Unexpected identifier
Here's the code that it's being run:
import { Client, Collection } from "discord.js";
import { readdir } from "fs-extra";
const client = new Client({
intents: ["GUILDS", "GUILD_MEMBERS", "GUILD_MESSAGES"],
});
client.commands = new Collection();
client.once("ready", async () => {
try {
const commandFiles = readdir("./src/commands").filter(
file.endsWith(".js"),
);
commandFiles.forEach(async (file) => {
import command from `./commands/${file}`;
client.commands.set(command.name, command);
});
} catch (err) {
console.error(err);
}
});
client.login(process.env.D_TOKEN);
I'm using "type": "module"
in the package.json, so that's not the problem, I think I might be using it wrong, if am I, how can I fix it?
Nodejs ver: 16.9.0 | Npm ver: 7.22 | Discord.js ver: 13.1.0
CodePudding user response:
Importing
If you're importing one asset from a group of exports, you must use {}
to wrap around the variable being imported.
import { command } from `.commands/${file}`;
If you ever intend to import an entire file you would use the following syntax:
import * as command from `.commands/${file}`;
However your current example will still throw an error since you can only import files (while using import/export
) via the namespace (very top of the file in this case)
Solutions
If you want to achieve importing outside the namespace you'll either need to use Dynamic Importing or require()
. Preferably the former.
1. import require
You can view This Example on how to use both import
and require()
in the same file. Note that there can be an alternative way of handling this when using Typescript.
2. Dynamic Importing (Recommended)
Use dynamic importing
// namespace
import { foo } from "./bar";
// This also works
async function someFunc() {
const { default:foo } = await import("./bar");
}