Skip to content

Commit 91e8832

Browse files
committed
fix(rsc): pre-include React peers in client env optimizeDeps
The client environment only had `react-dom/client` and the React Server DOM browser entry in `optimizeDeps.include`. React itself and crawled React-peer packages were discovered lazily as the browser requested modules, which re-runs the optimizer mid-load and changes the `?v=` hash on already-served chunks. The browser ends up with two distinct React module records, and `'use client'` libraries that synchronously call hooks in providers hit the wrong dispatcher (`React.H` is null), throwing `Invalid hook call`. Mirror the SSR/RSC env behaviour by including `react`, `react-dom`, `react/jsx-runtime`, `react/jsx-dev-runtime`, plus the React-peer packages from `crawlFrameworkPkgs`. Filter that list to packages with a client-resolvable entry so server-only React peers (e.g. `@vitejs/test-dep-client-in-server`) don't break dep optimization.
1 parent 65d378f commit 91e8832

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

packages/plugin-rsc/src/plugin.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,18 @@ function resolvePackage(name: string) {
111111
return pathToFileURL(require.resolve(name)).href
112112
}
113113

114+
function filterBareResolvable(packages: string[], root: string): string[] {
115+
const userRequire = createRequire(path.join(root, 'package.json'))
116+
return packages.filter((name) => {
117+
try {
118+
userRequire.resolve(name)
119+
return true
120+
} catch {
121+
return false
122+
}
123+
})
124+
}
125+
114126
export type { RscPluginManager }
115127

116128
/**
@@ -517,8 +529,15 @@ export default function vitePluginRsc(
517529
},
518530
optimizeDeps: {
519531
include: [
532+
'react',
533+
'react-dom',
534+
'react/jsx-runtime',
535+
'react/jsx-dev-runtime',
520536
'react-dom/client',
521537
`${reactServerDomPackageName}/client.browser`,
538+
// Without these, the client optimizer re-scans on first
539+
// request, drifting `?v=` hashes and duplicating React.
540+
...filterBareResolvable(result.ssr.noExternal, process.cwd()),
522541
],
523542
exclude: [PKG_NAME],
524543
},

0 commit comments

Comments
 (0)