SyntaxError: duplicate export of 'default' in JavaScript

avatar

Borislav Hadzhiev

Last updated: Mar 3, 2022

banner

Photo from Unsplash

SyntaxError: duplicate export of 'default' in JavaScript #

The error "Duplicate export of 'default'" occurs when we have more than 1 default export in a file. To solve the error, replace the second default export with a named export or move the value to another file to be able to use another default export.

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.js
// ⛔️ Error: SyntaxError: Duplicate export 'default' export default class A{} // 👈️ default export export default class 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.

index.js
export default class A {} // 👈️ default export export class B {} // 👈️ named export

And here is how you would import the variables into another file.

another-file.js
// 👇️ default and named import import A, {B} from './index'; console.log(A); // 👉️ [class A] console.log(B); // 👉️ [class B]

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.

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 default or named export.

Here is how you would convert the example above to use only named exports and imports.

index.js
export class A {} // 👈️ named export export class B {} // 👈️ named export

And here is how you would import the named exports.

another-file.js
// 👇️ named imports import {A, B} from './index'; console.log(A); // 👉️ [class A] console.log(B); // 👉️ [class B]

This is much better than having to remember which values you exported as default, and which named.

The less you have to think about implementation details, the more you can focus on domain-specific logic in your application.

Conclusion #

The error "Duplicate export of 'default'" occurs when we have more than 1 default export in a file. To solve the error, replace the second default export with a named export or move the value to another file to be able to use another default export.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.