ReferenceError: __dirname 未在 ES 模块作用域中定义

dws*_*ein 27 javascript import path

我正在阅读discord.js 上的本教程。当我按照编写的方式运行代码时,出现了诸如 之类的错误SyntaxError: Cannot use import statement outside a module

所以,我添加"type": "module"package.json

我设法让早期的例子运行起来。现在,我正在编写一段代码:

import dotenv  from "dotenv";
dotenv.config();
const token = process.env.DTOKEN;

// const fs = require('node:fs');
import fs from 'node:fs';
// const path = require('node:path');
import path from 'node:path';


// 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);
    // 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);
Run Code Online (Sandbox Code Playgroud)

我越来越:ReferenceError: __dirname is not defined in ES module scope

我认为 SO 没有太多进展。像这样的问题让我又回到了第一个问题。

我缺少什么?

dws*_*ein 45

本文有助于解决该问题:https://bobbyhadz.com/blog/javascript-dirname-is-not-define-in-es-module-scope

\n

这是文章中的代码:

\n
import path from \'path\';\nimport {fileURLToPath} from \'url\';\n\nconst __filename = fileURLToPath(import.meta.url);\n\n// \xef\xb8\x8f "/home/john/Desktop/javascript"\nconst __dirname = path.dirname(__filename);\nconsole.log(\'directory-name \xef\xb8\x8f\', __dirname);\n\n// \xef\xb8\x8f "/home/borislav/Desktop/javascript/dist/index.html"\nconsole.log(path.join(__dirname, \'/dist\', \'index.html\'));\n\n
Run Code Online (Sandbox Code Playgroud)\n


Jur*_*els 8

__filename__dirname根据Nodejs 文档,并且仅在 CommonJS 模块中可用。

使用fileURLToPath(import.meta.url)获取当前文件/模块的文件路径。如果您需要包含目录路径,请使用path.dirname()