Difference Between default export and named export in ES6 Modules

Harish Krishnan
3 min readJun 18, 2020

Traditionally in Javascript, we used a module pattern called CommonJs, which is familiar to people who have used Node.js. But as of ES6 we no longer need to rely on enclosing functions and closure as ES6 comes with first-class functional support. If you are using any front-end frameworks like React, Angular, or Vue then you are already using ES6 Modules.

When using those frameworks or NodeJs through Babel support, you might have imported files or components using the below syntax:

Syntax from React Native

The first line of import is an example of default export and the second line is an example of named export. If you have been using ES6 Modules recently, then you know that there can be only one default export in a file and there can be any number of named exports.

Before going deep into the difference between the two types of exports, for beginners the advantage of having default export is that we can import the whole module as one import and you can use it like below which you might have used in react:

React class-based component file

Also, it is not mandatory to import React from “react”. You can import in any name of your preference like import app from “react” as well.

In order to do a similar naming when using named exports, you have to use an alias. For example,

import { Component as c1 } from “react”

But the differences are much more than this if you dig deeper. I have created two files with below code :

index.js

I have created a file named index.js and have imported the number named export from file1.js and I am consoling the number. Here is the code for the file1:

file1.js

This file just declares a variable called number as exported as a named export. What do you expect the console.log to print? Any guesses?

If you think it is 50, you are wrong. The output will be 100 in the console.

Now change the named export to default export by changing these lines

import { number } from “./file1”; to import number from “./file1” in index.js

export { number }; to export default number; in file1.js

Now, what do you think will be the console log output? It is 50 this time.

Thus, here comes the important difference between the two. When we change the value after exporting it as a named export the latest value is taken when we reference those in other files. Whereas, default export takes the value at the point of exporting and thus is not changed. So beware of this important distinction as this might lead to a bug that is difficult to find.

I also take courses on Udemy. In case you like to get course updates please join the below email list or check out my Udemy Instructor profile.

--

--