L
L
low molecular macro2021-01-30 02:01:46
JavaScript
low molecular macro, 2021-01-30 02:01:46

What is the difference between module.exports and export default?

Found exactly the same question on stackoverflow , but never got the point. As far as I understand, both options give the same result, but I met the option with default only a couple of times.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
WbICHA, 2021-01-30
@WblCHA

Old: module.exports
New:export default

D
Dmitry Belyaev, 2021-01-30
@bingo347

module.exports is part of the CommonJS module system, the advantage of which is that it can be implemented in JS itself (you need the ability to load code synchronously), as is done, for example, in Node.JS, where this module system appeared. The downside is that from the point of view of the AST, all CommonJS constructs are ordinary JS constructs, such as calling the require function or accessing the module object, which means that various optimization and assembly tools have much fewer opportunities here (for example, webpack does not know how to trishake in CommonJS modules )
export default is part of the standard JS modules, which appeared in the standard only in 2015 and received a native implementation only in 2018-2019. And this has been its main disadvantage for a long time. Also, the downside is that the vast majority of modules on npm still do not have support for this standard, but are supplied only in CommonJS. But the unequivocal plus is that this is a native feature of the language, with all the consequences.
There is also a good article on the topic:
https://habr.com/en/company/domclick/blog/532084/

S
Sergey delphinpro, 2021-01-30
@delphinpro

Previously, there were no modules in javascript. I wanted it because it's convenient. Therefore, different systems were invented. CommonJS, AMD, UMD. AMD is the oldest. CommonJS was created specifically for NodeJS. UMD - universal, compatible with both previous ones.
All these require(), module.exportsare parts of the CommonJS modular system.
However, without native support for modules, all these systems are essentially crutches.
And then happiness came - native modules (ES Modules) were brought to javascript. Import / export, etc.
They got into the node in version 13 as an experimental feature, and already in version 14 - fully functional. In advanced browsers appeared even earlier.
In summary, today it is worth giving preference to ES Modules both in NodeJS and in browser development.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question