Named Export vs Default Export in ES6
ES6 provides us to import a module and use it in other files. In React one can use stateless components in other components by exporting the components from their respective modules.
ES6 provides two ways to export a module from a file: named export and default export.
Named Export: (export)
With named exports, one can have multiple named exports per file. Then import the specific exports they want to surrounded in braces. The name of the imported module has to be the same as the name of the exported module.
In the above Code, we created a Component and export it. In another file to use this component first we imported this component. You can see the name of the Component is the same in both files and bind it in curly braces.
In the above code, we created, two components and imported them in another file in curly braces with the same name.
Now You might be thinking that if we have multiple components in the same file then importing all components one by one would be a cumbersome task.
Import all the named and exports onto an object.
To import multiple components we use import * as all_Components from './Component'
We can put any name instead of all_Components. This is an object. To access all the components we use this name and then put a dot(.) then the Component name. You can see this as well in lines no:- 7, 8, 9.
Default Export: (export default)
One can have only one default export per file. When we import we have to specify a name and import like: The naming of import is completely independent in the export default and we can use any name we like.
In the above piece of code, we created a component with the name of Component and used it in the other file with the Random name.
If we have both named export as well as default export:-
If we have both naming conventions then first we use export default and then named export comma separated.
We created a function named export and a variable with export default. For using both first we import default export then put a comma and named export. You can refer to line no 2.
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object, or anything else.