I have referred all the questions in stackoverflow. But none of the suggested why and when to use default export.
I just saw that default can be metioned "When there is only one export in a file"
Any other reason for using default export in es6 modules?
Usage. I prefer to use default exports when the exported component is only going to be imported once, or if a file exports one thing. A good example would be a Router component.
Export default means you want to export only one value the is present by default in your script so that others script can import that for use. This is very much necessary for code Reusability.
Refactoring. Default exports make large-scale refactoring impossible since each importing site can name default import differently (including typos). On the contrary, named exports make such refactoring trivial.
Some differences that might make you choose one over the other:
Named Exports
Default Exports
This article does a nice job of explaining when it would be a good idea to use one over the other.
It's somewhat a matter of opinion, but there are some objective aspects to it:
You can have only one default export in a module, whereas you can have as many named exports as you like.
If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does
import example from "./example";
...but Joe does
import ex from "./example";
In contrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module. It's just
import { example } from "./example";
If there's a conflict where you want the example
export from two different modules, you can use as
to rename:
import { example as widgetExample } from "./widget/example";
import { example as gadgetExample } from "./gadget/example";
With a named export, the person importing it has to specify the name of what they're importing, which means they get a nice early error if they try to import something that doesn't exist.
If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.
You should almost always favour named exports, default exports have many downsides
Problems with default exports:
checkout these articles for a more detailed explanation:
https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad
https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
https://rajeshnaroth.medium.com/avoid-es6-default-exports-a24142978a7a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With