A module cannot have multiple default exports Error [Fixed]
# A module cannot have multiple default exports Error
The error "A module cannot have multiple default exports" occurs for 2reasons - having more than 1 default export in a file or having a glitch in yourIDE.
To solve the error, replace the second default export with a named export andreload your IDE if necessary.
If you don't have multiple default
exports in the file, try reloading your IDE. WebStorm and VSCode sometimes need a reboot.
Here is an example of how the error occurs.
index.ts
Copied!
const a = 'bobby';// βοΈ Error: A module cannot have multiple default exports.ts(2528)export default a; // ποΈ default exportconst b = 'hadz';export default b; // ποΈ default export
We can only have a single default export per file, so we have to move the seconddefault export to another file or convert it to a named export.
# Convert the second default export to a named export
Here is how you would convert the second export to a named export.
index.ts
Copied!
const a = 'bobby';// ποΈ default exportexport default a;// ποΈ named exportexport const b = 'hadz';
Here is how you would import the variables into another file.
another-file.ts
Copied!
// ποΈ default and named importimport a, { b } from './index';console.log(a); // ποΈ "bobby"console.log(b); // ποΈ "hadz"
We had to wrap the named import in curly braces. You can have only one default
export per file, but you can have as many named
exports as necessary.
If you don't want to use a named
export, move the second variable to aseparate file and make sure to stick to a maximum of 1
default export perfile.
In my experience, most real-world codebases exclusively use named exports and imports because they make it easier to leverage your IDE for auto-completion and auto-imports.
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 andimports.
index.ts
Copied!
// ποΈ named exportexport const a = 'bobby';// ποΈ named exportexport const b = 'hadz';
And here is how you would import the named exports.
index.ts
Copied!
// ποΈ named importsimport { a, b } from './index';console.log(a); // ποΈ "bobby"console.log(b); // ποΈ "hadz"
This is much better than having to remember which values you exported asdefault
, and which you exported as named
.
The less you have to think about implementation details, the more you can focuson domain-specific logic in your application.
# Restart your IDE
If none of the suggestions helped and you don't have multiple default exports ina single file, restart your code editor and your development server.
# Additional Resources
You can learn more about the related topics by checking out the followingtutorials: