Member-only story
Named vs Default Export
Exports help us organize and reuse the logics, below are comparison between two commonly used exports
Named export
//utility.js
export const sum = (a,b) => a + b;
//File1.js
import {sum} from './utility'
//File2.js
import * as utility from './utility'
utility.sum()
When imported the named export, we would similar to objects, so we can destructure directly with {}
or use same that object to an alias with * as utility
( we can use any variable name not necessarily utility)
console.log(typeof utility);
— object
we can access in the same we access an object.
Default export
// utility.js
export default (a, b) => a + b;
import sum from './utility'
As you can see there is no where we specified sum variable , but while importing we specified sum, and it will work and also no destructuring
That is we can use any name while importing a default export
import ABCD from './utility'
— ABCD will hold the default export of that file.
Named and default export in same file
We can also have named and default export in the same file
import Default , {named} from './somefile'
When to use what
- If the file hold only one element and that needs to be exported (Components, Directives) , we can go with default export , easier to export and import
- If multiple values needs to be exported, named export is preferable