Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use export default and export constant in JavaScript? [duplicate]

I am currently working on a react meteor project. I didn't find any clear documentation when to exactly use export default and when export const. Any opinions on this respectively when to use what and what are the differences?

like image 879
dom Avatar asked Sep 05 '25 03:09

dom


1 Answers

export default exports your module with no name, you can thus import it with this syntax :

export default MyModule = () => console.log('foo')

import MyModule from './MyModule' //it works
import foobar from './MyModule' //it also works,

export const exports with name :

export const MyModule = () => console.log('foo')

import MyModule from './MyModule' //returns empty object since there is no default export
import { MyModule } from './MyModule' //here it works because by exporting without 'default' keyword we explicitly exported MyModule
  • So, when you're exporting only one element from your module and you don't care of its name, use export default.
  • If you want to export some specific element from your module and you do care of their names, use export const
  • You should notice that you can combine both, in case you want to import a specific module by default and let the user import specific elements of your module.
like image 166
Pierre Criulanscy Avatar answered Sep 07 '25 22:09

Pierre Criulanscy