Avoid ES6 default exports

Rajesh Naroth
2 min readMar 25, 2019

--

This is opinionated nit picky territory. Just like the trailing comma discussion.

We are frontend developers with strong muscles for dealing with bad parts of JavaScript, CSS hacks and Browser quirks. We roll up our sleeves and just get the job done. That doesn’t mean we can’t move towards a more tranquil developer experience (DX). And sometimes that means shunning certain available features and sometimes an entire “class” 🤐of features. Just because it is there doesn’t mean it should be used. If there is a better way.

This is why I avoid default exports.

1. For non functions, you have to always remember to do it in a separate line

It is easy to do a default export for functions in a single line.

export default function sayHello() {
return "Hello";
}

For anything else, it is a two step process.

const sayHello = () => "Hello";
export default sayHello;
// You cannot do:
// export default sayHello = () => "Hello";

For developer experience, it is a small minus.

2. It is very easy to confuse default exports vs named ones while importing from the same package

Ever paused wondering if you have to do something like this

import { React, createRef } from 'react';

vs

import React, { createRef } from 'react';

That pause is bad DX. So is having to debug after making the wrong import. In the initial days, I have done it several times and faced the console wrath: “You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.”

3. It facilitates cleaner export aggregation

I constantly combine exports in index.js from a component or helper folder.

// index.jsexport { Title } from "./components/title";
export { Navigation } from "./components/Navigation;

With default exports, it is again a two step process.

// index.jsimport Title from "./components/title";
import Navigation from "./components/Navigation;
export { Title, Navigation };

Not a fan of this.

4. Importing named exports is less buggy

Because the following lines of code works perfectly but is wrong at many levels.

import Angular from "react";export default function Hello() {
return Angular.createElement("div", null, "Hello World");
}

Named exports precisely indicate what you are importing.

Exceptions

There are times you will need to use default exports such as when you have to do code splitting.

const ItemsContainer = React.lazy(() => import("../../items/components/ItemsContainer"));

In this case, ItemsContainer must be a default export.

--

--

Rajesh Naroth
Rajesh Naroth

Written by Rajesh Naroth

Frontend Architect, San Jose, CA

Responses (2)