When should I use the "default export" in JavaScript / TypeScript?

If we specify the default export:

export class Foo {} export default Foo; 

then we can omit the curly braces during import (as indicated in this answer ):

 import { Foo } from "foo"; // becomes: import Foo from "foo"; 

This is fine, but are there any non-stylistic reasons to prefer each other in some cases? For example, is there some kind of agreement or is it incompatible with certain instruments or has a different meaning?

(Based on this discussion and others, I understand that export default could come about as a way to handle the export of a single primary object (for example, $ ), which is now processed by import * as foo from "foo" . import * as foo from "foo" Also, it seems that the import syntax by the default does not provide consistent naming ( import fooAlias from "foo" ), while the standard import import { fooAlias } from "foo" will be compiled except that the alias was explicit ( Foo as fooAlias ). In addition, I could not find much information on when I should use one over the other.)

+5
source share
2 answers

There is nothing wrong with that. I prefer to export one thing, so by default it works for me most of the time. You can also use both options.

I try not to use default when using a cleaner functional approach or writing a set of static use functions.

So, when my module is really just a class, I like to use default . Note that I can still export other things.

 export default class Foo { } 

// some use module

 export function fooHelper() { } export function bazHelper() { } 
+2
source

the default export may allow you to rename the file upon import, so ...

foo.js

 export default class Foo{ constructor(){ } } 

may be import Bar from './foo'; in another file, this can be useful if you use the library and already have a specific Foo class.

You can also export the default and non-default values ​​to: import Foo, { someVariable, someMethod } from './foo';

0
source

Source: https://habr.com/ru/post/1236843/


All Articles