Repository navigation
Conversation
Vite's SSR build lowers a `require("react")` inside vendored CommonJS to a
runtime `__require("react")` (createRequire) because React is an SSR-external.
Once Nitro bundles React for a self-contained `.output/`, that require is left
dangling: it fails with `Cannot find module 'react'` when node_modules is not
shipped, or loads a duplicate React instance ("Invalid hook call") when it is.
Add an opt-in `experimental.cjsRequireRewrite` flag that rewrites such leaked
requires to the copy already bundled in the output. `"react"` targets the React
family; `true` covers any bundled dependency. Unresolved leaks warn instead of
shipping silently.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true📝 Walkthrough
🚥 Pre-merge checks | ✅ 4 | ❌ 1
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/unit/cjs-require.test.ts (1)
27-144: ⚡ Quick winAdd coverage for single-quoted leaked requires
Please add a case for
__require('react')(and/or another specifier) to lock in quote-agnostic rewrite behavior and avoid regressions.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit/cjs-require.test.ts` around lines 27 - 144, Add a new test case in the describe block after the first it("rewrites a leaked __require() to the bundled initializer") test to verify single-quoted leaked requires are handled correctly. Create a test similar to the existing one but use single quotes in the __require call (e.g., __require('react') instead of __require("react")) and verify that the rewrite logic still produces the correct import statement and variable assignment regardless of quote style. This ensures the rewrite behavior is quote-agnostic and prevents regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/build/plugins/cjs-require.ts`:
- Around line 28-29: The LEAK_RE regex pattern at the current location only
matches double-quoted require calls like __require("...") but fails to match
single-quoted variants like __require('...'). Update the LEAK_RE regex pattern
to match both single and double quotes around the require path argument.
Similarly, update the DEF_RE regex pattern (also mentioned in the review at line
85) to match both quote styles for the require definition pattern. Modify both
regex patterns to use a character class or alternation to capture both quote
types, ensuring that leak detection and rewriting work correctly regardless of
which quote style is used in the generated output.
---
Nitpick comments:
In `@test/unit/cjs-require.test.ts`:
- Around line 27-144: Add a new test case in the describe block after the first
it("rewrites a leaked __require() to the bundled initializer") test to verify
single-quoted leaked requires are handled correctly. Create a test similar to
the existing one but use single quotes in the __require call (e.g.,
__require('react') instead of __require("react")) and verify that the rewrite
logic still produces the correct import statement and variable assignment
regardless of quote style. This ensures the rewrite behavior is quote-agnostic
and prevents regressions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e93b040a-265d-4630-91e6-616d1a2cd1fc
📒 Files selected for processing (4)
src/build/plugins.tssrc/build/plugins/cjs-require.tssrc/types/config.tstest/unit/cjs-require.test.ts
| const LEAK_RE = /\b__require\(\s*"([^"]+)"\s*\)/g; | ||
| const DEF_RE = /\bvar (require_[A-Za-z0-9_$]+)\s*=[^\n]*__commonJS/g; |
There was a problem hiding this comment.
Handle single-quoted __require() calls too
LEAK_RE and the replacement regex only match __require("..."). If output uses __require('...'), the leak won’t be detected or rewritten, so runtime failures can persist in self-contained builds.
Suggested patch
-const LEAK_RE = /\b__require\(\s*"([^"]+)"\s*\)/g;
+const LEAK_RE = /\b__require\(\s*["']([^"'\\]+)["']\s*\)/g;
@@
- const requireRe = new RegExp(`__require\\(\\s*"${escapeRe(spec)}"\\s*\\)`, "g");
+ const requireRe = new RegExp(
+ `__require\\(\\s*["']${escapeRe(spec)}["']\\s*\\)`,
+ "g"
+ );Also applies to: 85-85
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/build/plugins/cjs-require.ts` around lines 28 - 29, The LEAK_RE regex
pattern at the current location only matches double-quoted require calls like
__require("...") but fails to match single-quoted variants like
__require('...'). Update the LEAK_RE regex pattern to match both single and
double quotes around the require path argument. Similarly, update the DEF_RE
regex pattern (also mentioned in the review at line 85) to match both quote
styles for the require definition pattern. Modify both regex patterns to use a
character class or alternation to capture both quote types, ensuring that leak
detection and rewriting work correctly regardless of which quote style is used
in the generated output.
commit: |
* fix(docs): declare use-sync-external-store to keep react linked in SSR bundle
Every client-side navigation into /docs returned 500 in production:
Error: Cannot find module 'react'
Require stack:
- /var/task/_ssr/rolldown-runtime-B4iAMlE-.mjs
The route loader's server function never resolved, so its `data` was
undefined and the route component threw "Cannot read properties of
undefined (reading 'path')". Direct hits on /docs/* were unaffected
because those pages are prerendered; only the `_serverFn` call made
during client-side navigation reached the crashing module.
`use-sync-external-store` is CJS-only and reaches the graph through
`@base-ui/react`, which `fumadocs-twoslash` started depending on in 3.3.
With pnpm the package is only visible through a nested `node_modules`,
so Vite's SSR pass cannot externalise it and inlines it instead —
leaving its internal `require("react")` as a runtime `__require("react")`
even though React is external. Nitro's second pass then bundles React
but cannot rewrite code that was already emitted, so the call survives
into `.vercel/output` and resolves against a `node_modules` that does
not exist on the Vercel function.
Declaring the package as a direct dependency hoists it to the root
`node_modules`, so Vite externalises it and Nitro links the require to
the bundled React copy. The built bundle now reads `require_react()`
instead of `__require("react")`.
This is a workaround for nitrojs/nitro#4171 (rolldown/rolldown#10643) and
can be dropped once nitrojs/nitro#4365 ships `experimental.cjsRequireRewrite`.
Co-Authored-By: Claude Opus 5 <[email protected]>
* chore: update dependencies
`taze -r -w major` across the workspace: vitest 5, @vitest/coverage-v8 5,
pnpm 12.3.4, tsdown 0.23, @tanstack/intent 0.3.8, @testing-library/jest-dom 7,
jsdom 30, lucide-react 1, fumadocs-twoslash 4, fumadocs 16.15.7,
@types/node 26, and assorted patch bumps. Followed by `pnpm dedupe`, which
collapses @trpc/server onto a single 11.18.0 copy — permix was resolving an
older 11.17.0 through its optional peer, and the two instances made the
tRPC middleware types structurally incompatible in the
express-trpc-react example.
TypeScript stays on ^6.0.3. Under 7.0.2 the permix build fails:
rolldown-plugin-dts rejects TS 7 with the `tsc` generator and falls back to
`tsgo`, which cannot emit declarations for the solution-style tsconfig.json
("tsgo did not generate dts file for ..."). svelte-check, @sveltejs/kit and
tsconfck also still want TS 5/6. Revisit once tsdown supports project
references with tsgo.
drizzle-orm is left alone — the registry request timed out during the run,
and the workspace intentionally tracks 1.0.0-rc rather than the 0.45.x
"latest" tag.
Co-Authored-By: Claude Opus 5 <[email protected]>
---------
Co-authored-by: Claude Opus 5 <[email protected]>
|
Rebased onto latest Two things to consider:
On the relation to #4094: they are complementary, not overlapping. #4094 makes a required package external and traced; this one handles the case where the package is already bundled. Worth noting in the issue that simply tracing This comment was written by an AI assistant on behalf of the Nitro maintainers. Please double-check anything that looks wrong. |
… to 5" This reverts commit 2d19b13. The demo's white screen is fixed at the source: dropping zustand/traditional takes use-sync-external-store out of the graph, so there is no inlined CJS package calling require("react") for Rolldown to leave behind. The demo bundle now contains no require shim at all. For the record, the workarounds that did not work here. Hoisting use-sync-external-store, react and react-dom to the root node_modules via publicHoistPattern produced byte-identical output, so the "not hoisted to root" condition in rolldown/rolldown#10643 is not what triggers it in a browser build. esmExternalRequirePlugin only rewrites requires for modules that are external, and React is bundled here. Rolldown's `inject` cannot reach the call either, because inside the CJS wrapper `require` is a bound local rather than a free identifier. The remaining option was nitro's cjsRequireRewrite (nitrojs/nitro#4365), a generateBundle pass that regex-rewrites the leaked call to the bundled initializer -- which would have meant maintaining surgery over minified output to keep a demo site alive. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # src/build/plugins.ts
…ackages on Vite 8 (#25523) We put pg into ssr.noExternal and that bundles `pg` and changes its CJS imports. In the second bundling step, Rolldown in Vite 8 emits `__require("pg-types")` for the dependency imports of pg (see [their migration guide](https://vite.dev/guide/migration#require-calls-for-externalized-modules) mentioning `esmExternalRequirePlugin` - also check the linked rolldown docs). As `__require` comes from `module.createRequire`, the bundlers think it's a normal function variable, and not an import. Therefore, a sub-dependency like `pg-types` cannot get into the final bundle. The plugin now bundles exactly these `require()` calls. The user's `ssr.external` entries and optional dependencies stay external. We didn't use `esmExternalRequirePlugin`, because it breaks function-exported CommonJS on Node < 23. Stacked on #25359. Fixes #25470 --- **Same problem: `__require()` of an external package stays in bundled CommonJS** - nitrojs/nitro#4171 - rolldown/rolldown#10643 - rolldown/rolldown#9407 **Workarounds and fixes in other tools** - nitrojs/nitro#4365 - vitejs/vite#22618 - vitejs/vite#23759 - vitejs/vite#21969 **Existing Sentry issues** - #24775 - #25339
|
stalled |
[ai assited] resolves #4171 via a workaround until upstream issue is fixed
Try:
"nitro": "https://pkg.pr.new/nitro@4365"inpackage.jsonnitro.config.tsaddexperimental: { cjsRequireRewrite: "react" }Vite's SSR build lowers a
require("react")inside vendored CommonJS (e.g.use-sync-external-store's shim, as shipped inside base-ui / recharts / reactflow) to a runtime__require("react")(createRequire), because React is an SSR-external. Once Nitro bundles React for a self-contained.output/, that require is left dangling:Cannot find module 'react'whennode_modulesisn't shipped (Docker runner, serverless), orInvalid hook call/ null dispatcher when it is —__requireloads a second React instance.Root cause is the Vite SSR lowering (pure Rolldown links the same nested require correctly); this is a downstream workaround.
This PR adds an opt-in
experimental.cjsRequireRewriteflag — agenerateBundlepass that rewrites leaked__require("x")to the copy ofxalready bundled in the output, so a single instance is used and the output stays self-contained."react"— targets the React family (react,react-dom,react/jsx-runtime, …).true— covers any bundled dependency that leaked a runtime require.Unresolved leaks emit a warning instead of shipping silently.