Skip to content

Instantly share code, notes, and snippets.

@Jamie-BitFlight
Created October 19, 2023 13:43
Show Gist options
  • Save Jamie-BitFlight/d15ad615249d60b02dfb72e0162ad5f9 to your computer and use it in GitHub Desktop.
Save Jamie-BitFlight/d15ad615249d60b02dfb72e0162ad5f9 to your computer and use it in GitHub Desktop.
'Dynamic require of "os" is not supported' or 'Dynamic require of "fs" is not supported' etc - can esbuild load dynamic imports? Yes!
const ESM_REQUIRE_SHIM = `
await(async()=>{let{dirname:e}=await import("path"),{fileURLToPath:i}=await import("url");if(typeof globalThis.__filename>"u"&&(globalThis.__filename=i(import.meta.url)),typeof globalThis.__dirname>"u"&&(globalThis.__dirname=e(globalThis.__filename)),typeof globalThis.require>"u"){let{default:a}=await import("module");globalThis.require=a.createRequire(import.meta.url)}})();
`;
const ESM_REQUIRE_SHIM = `
await (async () => {
const { dirname } = await import("path");
const { fileURLToPath } = await import("url");
/**
* Shim entry-point related paths.
*/
if (typeof globalThis.__filename === "undefined") {
globalThis.__filename = fileURLToPath(import.meta.url);
}
if (typeof globalThis.__dirname === "undefined") {
globalThis.__dirname = dirname(globalThis.__filename);
}
/**
* Shim require if needed.
*/
if (typeof globalThis.require === "undefined") {
const { default: module } = await import("module");
globalThis.require = module.createRequire(import.meta.url);
}
})();
`;
/** Whether or not you're bundling. */
const bundle = true;
/** Tell esbuild to add the shim to emitted JS. */
const shimBanner = {
"js": ESM_REQUIRE_SHIM
};
/**
* ESNext + ESM, bundle: true, and require() shim in banner.
*/
const buildOptions: BuildOptions = {
...common,
format: "esm",
target: "esnext",
platform: "node",
banner: bundle ? shimBanner : undefined,
bundle,
};
esbuild(buildOptions);
@Jamie-BitFlight
Copy link
Author

For sveltjs you can use this SHIM but, you also need to use this sveltjs pull request to be able to pass build options through to esbuild sveltejs/kit#9398

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment