我如何替换``在此代码中``
我正在关注 on discord.js 。我不得不将更改为
导入
节点:fs
和 node:path
。
但是,在第34行上,但是:( const命令= require(filepath);
)还有另一种要求语句在e5上丢弃相同的错误。我从 ReferenceError:在ES模块范围中未定义require,您可以使用导入
我也很想理解,为什么我看到的所有教程都使用 require
,但是我始终得到错误,必须转换为导入
。
这是我的代码:
import dotenv from "dotenv";
dotenv.config();
const token = process.env.DTOKEN;
// const fs = require('node:fs');
import fs from 'node:fs';
// https://bobbyhadz.com/blog/javascript-dirname-is-not-defined-in-es-module-scope
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
console.log(import.meta.url);
// const path = require('node:path');
import path from 'node:path';
// import path from 'path'
const __dirname = path.dirname(__filename);
// Require the necessary discord.js classes
import { Client, Collection, Intents } from "discord.js";
// const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
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); // *** here's the line with the error ***
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
}
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
// Login to Discord with your client's token
client.login(token);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使变量接收进口,您将不得不处理将要出现的承诺,对我来说这是有点工作,所以我还建议您重新进口,我也建议这样做。
要编写requient的导入,只需转到您的软件包。
Making a variable receive an import you will have to deal with the Promises that will come, for me it was a bit of work, so I redid the importations with require, I also recommend it.
To write imports with require just go to your package.json or package-lock.json and enter