Skip to content

fix: patch __dirname for ESM environments#217

Open
azohra wants to merge 1 commit intouber:masterfrom
azohra:fix/esm-dirname-compat
Open

fix: patch __dirname for ESM environments#217
azohra wants to merge 1 commit intouber:masterfrom
azohra:fix/esm-dirname-compat

Conversation

@azohra
Copy link

@azohra azohra commented Jan 17, 2026

Hey! Ran into this issue deploying to Cloudflare Workers and dug into the root cause.

The problem

The generated libh3.js uses __dirname for Node detection:

scriptDirectory=__dirname+"/"

This breaks in ESM environments where __dirname doesn't exist — Cloudflare Workers, Node ESM, Deno, Bun, etc.

The fix

Added a sed replacement in the build script (same approach as the existing document.currentScript patch from #117 and #163):

scriptDirectory=typeof __dirname!=="undefined"?__dirname+"/":""

Why it's safe

h3-js embeds memory init as a base64 data URI, so scriptDirectory falling back to "" works fine — it's never actually used to resolve file paths in bundled deployments.

Testing

  • Verified the sed pattern matches the generated out/libh3.js
  • Tested in Cloudflare Workers — works
  • Backwards compatible — Node CJS still gets __dirname as before

Fixes #216

Adds a post-processing sed to handle __dirname in ESM environments
where it's not defined (Cloudflare Workers, Node ESM, Deno, Bun).

Follows the same approach as the existing document.currentScript fix.

Fixes uber#216
@CLAassistant
Copy link

CLAassistant commented Jan 17, 2026

CLA assistant check
All committers have signed the CLA.

@azohra
Copy link
Author

azohra commented Jan 17, 2026

One note on approach — another option would be updating to Emscripten 3.x+ and adding -sUSE_ES6_IMPORT_META=1, which generates proper import.meta.url code instead of __dirname.

Went with the sed patch here since:

  • It's a minimal change that follows the existing pattern in the build script
  • Avoids the risk of updating the Emscripten toolchain (SDK 1.38.43 → 3.x is a big jump)
  • Can always do the Emscripten upgrade separately if desired

Happy to take either direction if maintainers prefer the toolchain update instead!

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

Successfully merging this pull request may close these issues.

__dirname is not defined when bundling h3-js for ESM environments

3 participants