docs: Add example for loading ESM from CommonJS#1236
Conversation
|
What to you think about adding this bootstrap approach as a way of loading a ESM package from a complete legacy commonjs codebase? // bootstrap.js
import('node-fetch').then(({
default: fetch,
Headers,
Request,
Response
}) => {
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
require('./app.js')
})Shorter version: // bootstrap.js
import('node-fetch').then(({
default: fetch,
...rest
}) => {
Object.assign(globalThis, rest, { fetch })
require('./app.js')
})This had me thinking... can you use preload?
|
|
If you're going to assign globals within an asynchronously executed function, then you might as well just const {
default: fetch,
Headers,
Request,
Response
} = await import("node-fetch")This would be best executed within asynchronous functions since CommonJS does not support top-level await. |
|
I where thinking about linking to https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c but it seems highly debatable about good and bad things and includes a few negative comments. There is also a few forks worth mentioning: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c/forks We also have: https://blog.sindresorhus.com/get-ready-for-esm-aa53530b3f77 and https://blog.sindresorhus.com/hello-modules-d1010b4e777b |
LinusU
left a comment
There was a problem hiding this comment.
Looked thru everything again, looks great 👍
|
@Richienb i fixed all your suggestions, please have another look |
|
is 40 lines of documentation what's preventing us from making v3 stable? |
kind of... this is the only thing left in the v3 milestone Only need 1 more acceptances from one of the maintainers and then we can release/tag v3 as stable ...Feels like some of the maintainers don't have much time or interest anymore that's why updates comes so rarely |
Purpose
Few ppl started complaining about beta-10 going ESM and are unable to load it. The purpose of this PR is to provide them a alternative method to load ESM modules from CJS
Changes
Have only updated some documents and suggested this way of loading fetch:
Additional information
There are both pro & cons with ESM.
Bundle all dependencies and having own instances is not desirable. It can make working with different whatwg:streams versions incompatible
docs:Should maybe link to a ESM upgrade guide blog/article of how to upgrade a cjs package to esm and how to use different compilers? ...any suggestions?can do this later...