Named exports vs Default exports

December 12, 2020


Named Exports vs Default Exports

The export statement is used in javascript to export our modules which can be used in other files with the help of the import statement.

There are 2 types of exports :

- Named exports

- Default exports

We can have multiple named exports in a file. Named exports are useful when you want to export multiple things from a file. While importing, the name of the module should be the same as the module name you are exporting.

On the other hand, default exports let us import the module with any name, it need not be the same name as the module name you are exporting. You can even export anonymous functions (which don't have a name at all). But, you can have only 1 default export in a file.

So, if there is a use case where you want to export only 1 module from a file, which one would you prefer ?

I like to use named export always, no matter if I'm exporting 1 module or multiple modules in a file. I prefer to use this import/no-default-export eslint rule in my projects.

Why do I prefer named export ? ๐Ÿค”

Firstly, it's easy to find out where all my exported modules are being used in my code base, as in named imports we strictly need to have the same name.

If I have a named export like this :

export const calcualateAverage = (...) => {...}

// I should import it with same name in someOtherFile.js
import { calcualateAverage } from "../utils/mathOperations"
// or
import { calcualateAverage as myNewCalculateAverageName } from "../utils/mathOperations"

I can easily find calcualateAverage.

If I had used a default export and imported this elsewhere with some other name like :

export default function calculateAverage = (...) => {...}

// importing in someOtherFile.js
import calcAverage from "../utils/mathOperations"

In this case, it's hard to find out that calculateAverage function is being used in some files as the imported name is different.

Especially, in react, it's easy to find where all the common components are used if I export it as a named export.

Helps in refactoring ๐Ÿ› 

If I'm refactoring the calculateAverage function, say, calculateAverageForFirst10Items, I would put effort to go and rename all the named imports, or else it will start throwing errors. But, in the case of default export, one may not put effort to refactor the import names in other places as it doesn't throw an error. This will lead to a code smell. You are calculating average only for the first 10 items but your import name says calcuateAverage. The function name doesn't precisely convey what exactly it does.

Hence, named exports are always safe to use, readable, and helps in maintaining large codebases.