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

问题描述

我正在使用 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,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"
    }
}

那应该会消除错误。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...