I love Named Export than Default Export.

I love Named Export than Default Export.

An opinion of my own upon using named export, and the reason behind why using named export over the default export in my point of view.

Subscribe to my newsletter and never miss my upcoming articles

Default Export

A default export can only export a single object, function, or variable and curly braces are omitted when importing in various files.

export default message() {
    console.log('Hello, Brother');
}

// in another file
import message from './message';

message(); 
// Result: 'Hello, Brother'

`

Important NOTE:

Default exports DO NOT require a specific value to be used when importing

export default message() {
    console.log('Hello, brother');
}

// in another file
import rahul from './message';

rahul(); // Output: 'Hello, Brother

in the above example, I exported the message() function and import it as a non-related name called rahul(). so it does not matter and it's only a convention.

example

import rock from './message'

// use as rock
rock()

Named Exports

Named exports allow us to share multiple objects, functions, or variables from a single file and were introduced with the release of ES2015.

export message() {
    console.log('Hello, Brother');
}

// more than one export
export const gift = 'The is a gift, not message';

// importing in another file
import { message, gift } from './message';

message(); // Output: 'Hello, Brother '

console.log(gift); // Output: 'The is a gift, not message'

In the above example, exported both functions individually and the best practice is the below one.

message() {
    console.log('Hello, Brother);
}

const gift = 'The is a gift, not message';

export { message, gift }

In the above example, I batched it together and exported it together.

Who won? Named or Default?

Looks like-named one won, because if your project gets bigger and bigger named one is prominent in helping me by adding more funcions in a single file and in a single export.

 
Share this
Proudly part of