Krzysztof Kaczor
28 Feb 2018
•
2 min read
ES2015 was the most important improvement to Javascript in years. Among many great features, it brought brand new module system — Ecma Script Modules which finally solved the problem of sharing code between files (modules) on a language level. It was a huge step forward but it needed to work with already existing modules, especially CommonJS used by node (require). That’s why it required some compromises, one of them is the existence of default exports. In this article, I want to explain why here at Neufund, we decided to ban default exports and use solely named ones.
Default exports don’t export any name ie. symbol that can be easily associated with an exported value. Named exports, on the other hand, are all about having a name (pretty obvious right 😂) . This makes possible for IDEs to find and import dependencies for you automatically, which is a huge productivity boost.
Default exports make large-scale refactoring impossible since each importing site can name default import differently (including typos).
// in file exports.js
export default function () {...}
// in file import1.js
import doSomething from "./exports.js"
// in file import2.js
import doSmth from "./exports.js"
On the contrary, named exports make such refactoring trivial.
Sometimes you can be tempted to export one huge object with many properties as default export. This is an anti-pattern and prohibits proper tree shaking:
// do not try this at home
export default {
propertyA: "A",
propertyB: "B",
}
// do this instead
export const propertyA = "A";
export const propertyB = "B";
Using named exports can reduce your bundle size when you don’t use all exported values (especially useful while building libs).
Default exports were introduced mostly for easier interoperability with thousands CommonJS modules that were exporting single values like:
module.exports = function() {...}
They don’t bring many benefits when used internally in your codebase, so please avoid them and thus make world a better place 😁
If you’re passionate about Front End development, check out the JavaScript Works job-board here!
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!