react-pdf icon indicating copy to clipboard operation
react-pdf copied to clipboard

[solution] __dirname is not defined in ES module scope

Open wojtekmaj opened this issue 1 year ago • 2 comments

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.

wojtekmaj avatar Jan 18 '24 10:01 wojtekmaj

Added to official documentation in https://github.com/diegomura/react-pdf-site/pull/128.

wojtekmaj avatar Feb 06 '24 13:02 wojtekmaj

@wojtekmaj, I'm having this issue using react-pdf on electron-vite. Could you tell more about how to workaround this issue?

ithustle avatar Jun 27 '24 10:06 ithustle