3 ms·
How does Bun support CJS and ESM in the same file? Is it transpiling CJS to ESM? Or is it transpiling ESM to CJS? ESM can use top-level await and CJS can't. So
by dfabulich 3y ago
How does Bun support CJS and ESM in the same file? Is it transpiling CJS to ESM? Or is it transpiling ESM to CJS?
ESM can use top-level await and CJS can't. So this can't possibly work, right?
// x.mjs
export const x = await 'x';
// y.cjs
console.log(require('./x.mjs').x);
And, indeed, it doesn't work in Bun. When I `bun y.cjs` it gives me this error message:
TypeError: require() async module "/tmp/x.mjs" is unsupported. use "await import()" instead.
… but using "await import()" instead is exactly what I was trying to avoid! I can use "await import()" in Node, too.
But it looks like it does work in Bun if I drop the `await` from y.mjs. So, is it just transpiling ESM to CJS, and failing out if the ESM uses top-level await?
EDIT: I see the documentation page https://bun.sh/docs/runtime/modules https://bun.sh/docs/runtime/modules has a "low-level details" section, explaining how import(CJS) works (by transpiling CJS to ESM), but it doesn't say anything there about how require(ESM) works, which is unfortunate, because that's by far the most interesting part! I've filed a doc bug on this. https://github.com/oven-sh/bun/issues/4601 https://github.com/oven-sh/bun/issues/4601
- deleted 3y ago[deleted]
- ayewo 3y agoI believe Jarred has answered this upthread: https://news.ycombinator.com/item?id=37437848 https://news.ycombinator.com/item?id=37437848