Is there any way to bundle CJS to ESM (or keep the `require` call) ?
When it comes to bundling a cjs module into an esm one with some cjs externals, esbuild will convert require to __require and print useful information at runtime. However, it also prevents other ESM based bundlers (rollup, vite (which is using rollup), ~~webpack~~) including esbuild itself to bundle the esm one again.
For example, in react-dom, there is require("react"), let's bundle it and externalize react:
export { render } from "react-dom"
> esbuild index.js --bundle --format=esm --external:react
...
var React = __require("react"); // will break other bundlers!
// except **webpack**, because it is based on cjs and will make `require` usable
...
> rollup index.js -e react -p node-resolve -p commonjs
import require$$0 from "react"; // looks ok
...
> tsc --module esnext --target esnext --moduleResolution node
// no, tsc doesn't do bundle
// but if you give it cjs code, it is likely to not change it
// input
var React = require("react");
// output
var React = require("react"); // not break other bundlers
Update: https://gist.github.com/hyrious/7120a56c593937457c0811443563e017
Any official saying on this?
Still actual in 2025