Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Default Exports vs Named Exports
Vladimir Vovk
Vladimir Vovk

Posted on

     

Default Exports vs Named Exports

exportdefaultfunctionA(){}// vsexportfunctionA(){}
Enter fullscreen modeExit fullscreen mode

I think that both methods are good. But I can see some advantages of named exports.

Named exports will not allow to implicitly change the import name

// No error with default exportimportButtonfrom'../components/Text'// now we have a "Button" component// which is actually a "Text" component// TypeScript will throw and error// if import and export names don't matchimport{Button}from'../components/Text'// we will get an error here
Enter fullscreen modeExit fullscreen mode

Named exports are easier to re-export and organise

Imagine we have several UI components insidecomponents folder. Each component in a separate file:components/Header.tsx,components/Text.tsx,components/Button.tsx, etc.

Now to be able to import these components asimport { Header, Text, Button } from '../components' we just need to create thecomponents/index.ts.

export*from'./Header'export*from'./Text'export*from'./Button'
Enter fullscreen modeExit fullscreen mode

Compare to the default exports where will need to write:

export{defaultasHeader}from'./Header'export{defaultasText}from'./Text'export{defaultasButton}from'./Button'
Enter fullscreen modeExit fullscreen mode

Named exports are shorter to write

exportfunctionComponent(){}// orexportconstComponent=()=>{}
Enter fullscreen modeExit fullscreen mode

Compared to default exports:

exportdefaultfunctionComponent(){}// orconstComponent=()=>{}exportdefaultComponent
Enter fullscreen modeExit fullscreen mode

If you have any questions or comments, please post them below, press 💖 button and happy hacking! 🙌🏻

Credits

Photo bySergey Sokolov onUnsplash

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Heya! 👋 I am passionate about Mobile and Web technologies, React Native, React, building beautiful user experiences, and making the world a better place.
  • Location
    Planet Earth
  • Joined

More fromVladimir Vovk

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp