Embrace ESM in Node examples #191
Unanswered
Josh-Cena
asked this question in
Code examples
Replies: 2 comments 3 replies
-
How big would this be? I have looked for |
Beta Was this translation helpful? Give feedback.
1 reply
-
Current state of CJS/ESM in node.js:
We can provide both cases in all examples in MDN and even more: use prefixes + submodules like this: |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This came out of mdn/content#13113 (comment) and is in some sense related to #143.
After Node 12 EOL, all LTS Node versions support unflagged ESM (short for ECMAScript modules). This replaces the legacy CJS (short for CommonJS) module system (although the latter is not going away either).
The interoperation between CJS and ESM in Node has been a long-standing issue and is widely regarded a pain point of Node. In summary: if the current module is CJS, it can't import anything that's ESM without using dynamic import (which is async and therefore can't be at the top level, unlike
require
which is sync); if the current module is ESM, it generally can import CJS the same way as before, although it may not be able to import all named exports, but have to import the entiremodule.exports
as default import.The fact that CJS can't import ESM means that as soon as your dependency is ESM-only, you either have to pin your dependency to an older version, or you have to re-structure your code to accommodate an async dynamic import, or you have to convert your own codebase to ESM. These days, more and more dependencies are migrating to ESM. I have written some more motivation here: facebook/docusaurus#6520. Since that's tied to a real-world project, it would offer more insight into how it impacts production.
To maximally ensure forward compatibility and avoid confusion from new users, I suggest MDN code examples embrace ESM as well. Due to the simple nature of our code, it shouldn't take much besides converting
require
toimport
andmodule.exports
toexport
. If possible, we can also add a page explaining the difference between CJS and ESM and how they interoperate—I haven't seen many great resources out in the wild.cc @teoli2003 @hamishwillee @mdn/yari-content-javascript
Beta Was this translation helpful? Give feedback.
All reactions