If we specify a default export:
export class Foo {}
export default Foo;
then we can omit curly braces during import (as noted in this answer):
import { Foo } from "foo"; // becomes:
import Foo from "foo";
That's fine, but is there any non-stylistic reason to prefer one over the other in particular cases? For example, is there some convention, or is one incompatible with certain tools, or does one have a different meaning?
(Based on this discussion and others, my understanding is that export default
might have arisen as a way of handling the export of a single, primary object (like $
), which is now handled by import * as foo from "foo"
. Also, it seems the default import syntax does not enforce consistent naming (import fooAlias from "foo"
), while the standard import import { fooAlias } from "foo"
would be a compilation error unless the alias was explicit (Foo as fooAlias
). Apart from that, I haven't been able to find much information on when I should use one over the other.)
There's no right or wrong here. I prefer to export one thing so default works for me most of the time. You can also use both too.
I tend to not use default
when taking a more pure functional approach or writing a set of static util functions.
So when my module is really just a class, I like to use default
. Notice I can still export other things.
export default class Foo {
}
// some util module
export function fooHelper() {
}
export function bazHelper() {
}
exporting default can allow you to rename the file on import so...
foo.js
export default class Foo{
constructor(){
}
}
can be import Bar from './foo';
in another file, this could be useful if you're using a library and already have a class Foo defined.
You can also export a default and a non default such that:
import Foo, { someVariable, someMethod } from './foo';
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