将 CommonJS 默认导出导入为命名导出/无法加载 ES 模块

Import CommonJS default exports as named exports / Cannot load ES module

我正在使用 TypeScript 使用 discord.js 制作一个机器人,但在尝试 运行 结果 JavaScript.

时出现以下错误
import { Client, FriendlyError, SQLiteProvider } from 'discord.js-commando';
                 ^^^^^^^^^^^^^
SyntaxError: Named export 'FriendlyError' not found. The requested module 'discord.js-commando' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'discord.js-commando';
const { Client, FriendlyError, SQLiteProvider } = pkg;

进行这些修改后,出现此错误:

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\Eliqn\projects\He2\dist\commands\general\information.js
require() of ES modules is not supported.
require() of C:\Users\Eliqn\projects\He2\dist\commands\general\information.js from C:\Users\Eliqn\projects\He2\node_modules\require-all\index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename information.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\Eliqn\projects\He2\package.json.

information.js:

export default class Information extends Command {
    /* ... */
}

information.js 正在使用 .registerCommandsIn(join(dirname(fileURLToPath(import.meta.url)), 'commands')); 导入。所以我尝试了两种解决方案:如果我按照消息的建议删除 "type": "module",我会得到 SyntaxError: Cannot use import statement outside a module,如果我将扩展名更改为 .cjs,它最终会加载文件,但我没有不明白为什么这是必要的,也不知道如何将特定文件输出为 .cjs 而不是 .js。尽管如此,该命令仍未正确注册。

如果有用,这是我的tsconfig.json:

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "module": "ES2020",
        "moduleResolution": "Node",
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "outDir": "dist",
        "target": "ES2020"
    }
}

我认为应该有更直接的方法来做到这一点,但我发现模块非常混乱。

您在代码中使用 ESM 有什么原因吗?您可以像这样配置 TypeScript 以使用 CommonJS 模块:

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "module": "CommonJS", // CommonJS
        "moduleResolution": "Node",
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "outDir": "dist",
        "target": "ES2020"
    }
}

这应该可以消除错误。