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

Polyfill import.meta.url when output format is cjs #1633

Closed
egoist opened this issue Sep 24, 2021 · 2 comments
Closed

Polyfill import.meta.url when output format is cjs #1633

egoist opened this issue Sep 24, 2021 · 2 comments

Comments

@egoist
Copy link

egoist commented Sep 24, 2021

This is the default behavior of Rollup so I think maybe esbuild should also add this 🤔

CleanShot 2021-09-24 at 23 21 56@2x

@evanw
Copy link
Owner

evanw commented Oct 15, 2021

So esbuild generally doesn't do polyfills. It also doesn't polyfill node's built-in fs module, for example. Instead esbuild is generally only concerned about syntax features. This is broadly because syntax features are universal but the details of what polyfills you need or what they should do are specific to your situation. Instead esbuild provides general-purpose mechanisms that let you bring your own polyfills. For example:

$ cat import.meta.url-polyfill.js
export const import_meta_url =
  typeof document === 'undefined' ? new (require('url'.replace('', '')).URL)('file:' + __filename).href :
    (document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href)

$ echo 'console.log(import.meta.url)' | esbuild --bundle --format=cjs --define:import.meta.url=import_meta_url --inject:./import.meta.url-polyfill.js | node
file:///[stdin]

You can read more about how to do this here: https://esbuild.github.io/api/#using-inject-with-define. Closing since I believe this to be out of scope.

@antongolub
Copy link

antongolub commented Sep 12, 2024

@evanw ,

new (require('url'.replace('', '')).URL or new (require('u' + 'rl').URL

Why do we need this trick?

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

3 participants