Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] support createRequire #1828

Open
loynoir opened this issue Dec 6, 2021 · 4 comments
Open

[Feature] support createRequire #1828

loynoir opened this issue Dec 6, 2021 · 4 comments

Comments

@loynoir
Copy link

loynoir commented Dec 6, 2021

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
Copy link
Owner

evanw commented Dec 7, 2021

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
Copy link

millsp commented Jun 9, 2022

It seems this has been implemented in Webpack 30 days ago
webpack/webpack#14228
swc-project/swc#4101

@LZQCN
Copy link

LZQCN commented Apr 8, 2024

#1921 (comment)
This seems to be a temporary solution

@markus-incisive
Copy link

I'm currently hijacking the require variable to do this, and it works for my purposes.

/* index.mts */
import { createRequire } from 'node:module'

let foo

try {
  const originalRequire = require
  require = createRequire(__filename)
  foo = require('path/to/foo')
  require = originalRequire
} catch (error) {
  console.error(error)
  process.exit(1)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants