Jonathan Pepin

Anti Pattern - ES6 default exports

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:

classFoo{}exportdefaultFoo;

And then import this module from another file with:

importFoofrom'./foo';

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

importFoo,{Bar,Baz}from'./foo';

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

importMyFoofrom'./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:

classFoo{}exportFoo;

and import them as normal modules:

import{Foo}from'./foo';

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

import{FooasMyFoo}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.