javascript 参考错误:ES模块作用域中未定义__dirname

ss2ws0br  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(282)

我正在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);

我得到:ReferenceError: __dirname is not defined in ES module scope
我看不出SO有什么可做的,像this one这样的问题只是让我回到了原点。
我错过了什么?

vawmfj5a

vawmfj5a1#

本文有助于解决此问题:https://bobbyhadz.com/blog/javascript-dirname-is-not-defined-in-es-module-scope
下面是文章中的代码:

import path from 'path';
import {fileURLToPath} from 'url';

const __filename = fileURLToPath(import.meta.url);

// 👇️ "/home/john/Desktop/javascript"
const __dirname = path.dirname(__filename);
console.log('directory-name 👉️', __dirname);

// 👇️ "/home/borislav/Desktop/javascript/dist/index.html"
console.log(path.join(__dirname, '/dist', 'index.html'));
uqcuzwp8

uqcuzwp82#

__dirname__filenamerequire不存在于ES模块中。只有当您将模块作为公共JS模块运行时,它们才可用。
要解决这个问题,您需要使用像@subbu963/esm-polyfills这样的polyyfill对上述变量进行多边形填充
然后使用运行nodejs脚本
node -r @subbu963/esm-polyfills your-script.js
更多信息:https://lordofthethings.xyz/how-to-fix-referenceerror-__dirname/__filename/require-is-not-defined-in-es-module-scope/

披露:我拥有并维护@subbu963/esm-polyfillshttps://lordofthethings.xyz

相关问题