JavaScript has two types of exports: normal[1] and default.
EDIT: JavaScript has two types of export syntaxes>
JavaScript has two types of exports: normal and default.
No, not really. JavaScript has only one kind of export structure. It has different syntaxes though.
export default function x() {}
is just a shorthand notation for function x(){}; export { x as default }
.
import x from '…'
is just a shorthand notation for import { default as x } from '…'
.
The difference between your the two module exports you discussed is much bigger than the single default
keyword. They only look so similar because you used shorthand notations. Fully spelled out, it's
export {
Foo as Foo,
Bar as Bar,
} // a declaration
vs
export default ({
Foo: Foo,
Bar: Bar,
}); // an object literal
Both normal exports and default exports have the same functionality - they can be imported into a namespace, and they can be destructured into smaller pieces.
No, they don't. Imports provide aliases for the exported variable declarations, there's no destructuring - and you cannot do that to properties of a default-exported object.
What are the reasons JavaScript has default exports, instead of sticking with just normal exports and having the import syntax be the following?
See https://esdiscuss.org/topic/moduleimport. The default-export syntax provides a shorthand syntax for exporting under the special name default
(which is not a valid variable name otherwise), as it is a quite common use case to export only a single thing from a module. It doesn't require explicitly naming a value when there is only one in this module anyway. In this regard, it has very much the purpose you envisioned for your export only
suggestion, but it is only one export not providing a full namespace of multiple aliasable exports.