Context
JavaScript has two types of exports: normal[1] and default.
EDIT: JavaScript has two types of export syntaxes
Normal exports
class Foo {...}
class Bar {...}
export {
Foo,
Bar,
};
or
export class Foo {...}
export class Bar {...}
Normal exports can be imported in two ways: namespace[1] imports and named imports (looks similar to destructuring).
Namespace imports
import * as Baz from './baz';
Named imports
import {Foo, Bar} from './baz';
Default exports
class Foo {...}
class Bar {...}
export default {
Foo,
Bar,
};
Default exports can also be imported in two ways: namespace imports and named imports (in a hackish way using destructuring in a separate statement)
Namespace imports
import Baz from './baz';
Named imports
import temp_Baz from './baz';
const {Foo, Bar} = temp_Baz;
Question
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.
1) What are the reasons JavaScript has default exports, instead of sticking with just normal exports and having the import syntax be the following?
import <varName> from <location>;
<varName>
would allow destructuring like any variable assignment, without a special "named" import.
Node.js managed without default exports, and the only additional change would be to allow exporting of a single value:
module.exports = class Foo {...}
This could be done with export =
or export only
or something similar:
export only class Foo {...}
So now you might ask, what is the difference between export only
and export default
?
export only
exports could be imported with the same syntax, whereas export default
requires a different importing syntax. To allow both syntaxes to work for the module user, the module must both export
and export default
the same items (which is something I do in all my modules).
export default
is renamed to export only
which is a better term in my opinion (less confusing; clearer)
2) All the differences listed above are pros. Are there any other differences that are cons? Or can any of the above differences also be cons?
Edit
It seems I misunderstood the intended use for export default
.
It's for adding a default export on top of the regular exports.
So I'd now like to know when are default exports used? Although I probably shouldn't add more to this question.
If the only use for default exports is if your module only has a single item to export, then this question still applies.
Edit 2
Now it seems that the intended use is if a module only exports a single item. So my question still applies. Why not replace default exports with export only
, removing the need for an additional default import syntax?
Notes
[1] I am not sure if this is the correct term to use
See Question&Answers more detail:
os