我如何替换' ' ' ' require() ' ' ' '在这段代码?



我正在学习一个关于Discord.js的教程。我不得不将node:fsnode:pathrequire改为import

然而,在第34行:(const command = require(filePath);)中,有另一个require语句抛出了关于E5的相同错误。我从这类文章的理解是import总是在文件的开头运行。那么,如何处理这个错误呢?ReferenceError: require is not defined in ES module scope, you can use import instead

我也很想了解,为什么我看到的所有教程都使用require,但我总是得到一个错误,不得不转换为import

下面是我的代码:

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

让一个变量接受导入,你将不得不处理即将到来的承诺,对我来说这是一点工作,所以我用require重新做了导入,我也推荐它。

要使用require编写导入,只需到您的包中。Json或包锁。Json并输入

"type": "commonjs",

最新更新