Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use `export default`in JavaScript / TypeScript?

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.)

like image 529
mk. Avatar asked Oct 30 '22 14:10

mk.


2 Answers

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() {
}
like image 88
pbo Avatar answered Nov 08 '22 04:11

pbo


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';

like image 43
glued Avatar answered Nov 08 '22 02:11

glued