Last updated: Feb 27, 2024
Reading timeยท2 min
The error "A module cannot have multiple default exports" occurs for 2 reasons - having more than 1 default export in a file or having a glitch in your IDE.
To solve the error, replace the second default export with a named export and reload your IDE if necessary.
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.
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
We can only have a single default export per file, so we have to move the second default export to another file or convert it to a named export.
Here is how you would convert the second export to a named export.
const a = 'bobby'; // ๐๏ธ default export export default a; // ๐๏ธ named export export const b = 'hadz';
Here is how you would import the variables into another file.
// ๐๏ธ default and named import import 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 a
separate file and make sure to stick to a maximum of 1
default export per
file.
You also don't have to think about which members are exported with a default
or a named
export.
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 you exported as named
.
The less you have to think about implementation details, the more you can focus on domain-specific logic in your application.
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.
You can learn more about the related topics by checking out the following tutorials: