react-pdf
react-pdf copied to clipboard
[solution] __dirname is not defined in ES module scope
Describe the bug
When building react-pdf in ESM mode, you may encounter an error:
__dirname is not defined in ES module scope
This is because yoga-layout uses __dirname
in their code. This has already been reported to them: https://github.com/facebook/yoga/issues/1559
To work around this issue, for now, consider using inject
option in esbuild:
cjs-shim.ts
import { createRequire } from 'node:module';
import path from 'node:path';
import url from 'node:url';
globalThis.require = createRequire(import.meta.url);
globalThis.__filename = url.fileURLToPath(import.meta.url);
globalThis.__dirname = path.dirname(__filename);
esbuild.ts
await esbuild.build({
// …
inject: ['cjs-shim.ts'],
// …
});
If you're not using esbuild, you may manually import the cjs-shim.ts
file BEFORE react-pdf is loaded.
Added to official documentation in https://github.com/diegomura/react-pdf-site/pull/128.
@wojtekmaj, I'm having this issue using react-pdf on electron-vite. Could you tell more about how to workaround this issue?