【问题标题】:Discord.js with ES6: SyntaxError: Unexpected identifierDiscord.js 与 ES6: SyntaxError: Unexpected identifier
【发布时间】:2021-09-21 22:03:40
【问题描述】:

我正在将我的机器人转换为 ES6 语法。由于我不能使用:const command = require(`./commands/${file}`),我尝试使用import command from `./commands/${file}`;。它没有用,它给了我一个奇怪的错误:

file:///D:/Documenti/Coding/Discord/XayBot/XayBotMain/src/index.js:15
  import command from `./commands/${file}`;
         ^^^^^^^
SyntaxError: Unexpected identifier

这是它正在运行的代码:

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);

我在 package.json 中使用"type": "module",所以这不是问题,我想我可能使用错了,如果是,我该如何解决?

Nodejs 版本:16.9.0 | Npm 版本:7.22 | Discord.js 版本:13.1.0

【问题讨论】:

    标签: node.js ecmascript-6 discord.js


    【解决方案1】:

    正在导入

    如果您要从一组导出中导入一个资产,则必须使用 {} 包裹要导入的变量。

    import { command } from `.commands/${file}`;
    

    如果您打算导入整个文件,您可以使用以下语法:

    import * as command from `.commands/${file}`;
    

    但是您当前的示例仍然会抛出一个错误,因为您只能通过命名空间导入文件(在使用 import/export 时)(此文件的最顶部)案例)


    解决方案 如果要在命名空间之外实现导入,则需要使用Dynamic Importingrequire()。最好是前者。

    1.导入 + 要求

    您可以查看This Example,了解如何在同一文件中同时使用importrequire()。请注意,在使用 Typescript 时,可以有另一种处理方式。

    2。动态导入(推荐)

    使用动态导入

    // namespace
    import { foo } from "./bar";
    
    // This also works
    async function someFunc() {
       const { default:foo } = await import("./bar");
    }
    

    【讨论】:

    • OP 确实使用了有效的文件名
    • 我指的是变量的导入,不是模板字符串路径。
    猜你喜欢
    • 2020-12-30
    • 2019-05-08
    • 2019-10-06
    • 2021-06-09
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多