esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Is there any way to bundle CJS to ESM (or keep the `require` call) ?

Open hyrious opened this issue 4 years ago • 3 comments

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

hyrious avatar Jul 23 '21 23:07 hyrious

Update: https://gist.github.com/hyrious/7120a56c593937457c0811443563e017

hyrious avatar Jan 13 '22 03:01 hyrious

Any official saying on this?

zheeeng avatar Feb 28 '22 09:02 zheeeng

Still actual in 2025

bodia-uz avatar Jul 01 '25 15:07 bodia-uz