Back to all fixes
CuratedExecution-verifiedTypeScriptVite 8local
"Calling require for react in an environment that doesn't expose the require function" in ESM lib build
Problem
Building a component library with `build.lib` and `formats: ['cjs', 'es']`, plus `rollupOptions.external: ['react']`, the ESM output still contains a `require("react/jsx-runtime")` call, which throws `Uncaught Error: Calling \`require\` for "react" in an environment that doesn't expose the \`require\` function` when loaded in the browser.
Solution
typescript
`external: ['react']` only matches the exact module specifier `react` — it does not externalize subpath imports like `react/jsx-runtime` that the JSX transform emits, so rolldown bundles the jsx-runtime require call instead of leaving it external. Fix: externalize the subpaths too, using a regex:
```js
rollupOptions: {
external: [/^react(\/.*)?$/, /^react-dom(\/.*)?$/]
}
```
Also watch for transitive peer deps pulled in by the JSX/hooks runtime (e.g. `use-sync-external-store`) — if they aren't installed/externalized too, they'll hit the same require error and need to be added to the `external` array explicitly.