evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
37.95k stars 1.14k forks source link

[Feature] support `createRequire` #1828

Open loynoir opened 2 years ago

loynoir commented 2 years ago
import { createRequire } from 'module'
const require = createRequire(import.meta.url)

/**
 * @type {typeof ReadableStream}
 */
let RS: typeof ReadableStream
if (typeof ReadableStream !== 'undefined') {
  RS = ReadableStream
} else {
  try {
    RS = require('node:stream/web').ReadableStream
  } catch {
    RS = require('web-streams-polyfill/dist/ponyfill.js').ReadableStream
  }
}

export default RS
$ esbuild --bundle XXX.mts
The package "module" wasn't found on the file system but is built into node. Are you trying to
bundle for node? You can use "--platform=node" to do that, which will remove this error.
$ esbuild src/index.mts --bundle --platform=node
... web-streams-polyfill/dist/ponyfill.js is not bundled ...
$ # remove `createRequire`, let `require` global
web-streams-polyfill/dist/ponyfill.js is bundled

But, reference to a global variable require within ESM, I think it's not in standard?

evanw commented 2 years ago

Do other bundlers support this too? I mainly try to have esbuild follow existing conventions instead of inventing new ones. I don't think esbuild should do something like this without e.g. Webpack doing this too, because I don't want to create new conventions and fragment the community.

millsp commented 2 years ago

It seems this has been implemented in Webpack 30 days ago https://github.com/webpack/webpack/issues/14228 https://github.com/swc-project/swc/issues/4101

LZQCN commented 5 months ago

https://github.com/evanw/esbuild/issues/1921#issuecomment-1898197331 This seems to be a temporary solution