一个模块不能有多个默认导出错误
A module cannot have multiple default exports Error
出现错误“一个模块不能有多个默认导出”的原因有 2 个——文件中有超过 1 个默认导出或 IDE 中出现故障。
要解决该错误,请将第二个默认导出替换为命名导出,并在必要时重新加载您的 IDE。
default
如果文件中没有多个导出,请尝试重新加载 IDE。WebStorm 和 VSCode 有时需要重启。下面是错误如何发生的示例。
const a = 'bobby'; // ⛔️ Error: A module cannot have multiple default exports.ts(2528) export default a; // 👈️ default export const b = 'hadz'; export default b; // 👈️ default export
每个文件只能有一个默认导出,因此我们必须将第二个默认导出移动到另一个文件或将其转换为命名导出。
将第二个默认导出转换为命名导出
以下是将第二个导出转换为命名导出的方法。
const a = 'bobby'; // 👇️ default export export default a; // 👇️ named export export const b = 'hadz';
这是将变量导入另一个文件的方法。
// 👇️ default and named import import a, { b } from './index'; console.log(a); // 👉️ "bobby" console.log(b); // 👉️ "hadz"
我们必须用大括号将命名的导入包起来。每个文件只能有一个default
导出,但您可以根据需要进行多次named
导出。
如果您不想使用named
导出,请将第二个变量移动到一个单独的文件,并确保坚持1
每个文件的最大默认导出。
You also don’t have to think about which members are exported with a default
or a named
export.
# Only using named exports
Here is how you would convert the example above to use only named exports and
imports.
// 👇️ named export export const a = 'bobby'; // 👇️ named export export const b = 'hadz';
And here is how you would import the named exports.
// 👇️ named imports import { a, b } from './index'; console.log(a); // 👉️ "bobby" console.log(b); // 👉️ "hadz"
This is much better than having to remember which values you exported as
default
, and which as named
.
The less you have to think about implementation details, the more you can focus
on domain-specific logic in your application.
# Restart your IDE
If none of the suggestions helped and you don’t have multiple default exports in
a single file, restart your code editor and your development server.
# Additional Resources
您可以通过查看以下教程来了解有关相关主题的更多信息: