Avoid ES6 default exports

Rajesh Naroth
Mar 25 · 2 min read

This is nit picky territory. Yes, we are frontend developers that puts up with so much crap. We have 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 would 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

Ever paused wondering if you have to do something like this

import { React, useState } from './App';

vs

import React, { useState } from './App';

That pause is bad DX. So is having to debug after making the wrong import. I have done it several times and faced the browser 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.”

I have seen the pattern of using default export for Components and then combining them all into named exports in index.js.

// Title.js
const Title = () => "hello";
export default Title
// Navigation.js
const Navigation = () => <ul>...</ul>;
export default Navigation
//index.js
import Title from "./title";
import Navigation from "./Navigation;
export { Title, Navigation};

Instead, how about this:

// Title.js
export const Title = () => "hello";
// Navigation.js
export const Navigation = () => <ul>...</ul>;
// index.js
import { Title } from "./title";
import { Navigation } from "./Navigation;
export { Title, Navigation };

I think it is much cleaner to stick to a single syntax model of import. And with libraries (like React), we just have to bite the bullet. In my team, as a rule of thumb, there are no default exports.