The blog ofJonathan Pepin

Anti Pattern - ES6 default exports

2017-12-05

The new ES6 module system offers a built in export system coming with a better syntax than previously used CommonJS and AMD modules.

You can now export modules with the following syntax:

class Foo {}
export default Foo;

And then import this module from another file with:

import Foo from './foo';

If you need to import more things for this module, the syntax would be different:

import Foo, {Bar, Baz} from './foo';

Because Foo is the default export, the import can happen with an implicit different name:

import MyFoo from './foo';

As code grows, this becomes an issue as the relation between MyFoo and Foo is unclear. Even if engineers are diligent in using the same name, a refactor renaming the original module might miss some places when it's imported and this issue would appear.

Instead, never export modules as default:

class Foo {}
export Foo;

and import them as normal modules:

import {Foo} from './foo';

If a different name is required, then the renaming is explicit:

import {Foo as MyFoo} from './foo';

I just went into a cleanup to remove all default exports on one of our codebase, and just that proved useful and made the code cleaner and safer.