diff --git a/packages/react-start/src/plugin/vite.ts b/packages/react-start/src/plugin/vite.ts index 3d47aad887a..f6481cb73c7 100644 --- a/packages/react-start/src/plugin/vite.ts +++ b/packages/react-start/src/plugin/vite.ts @@ -45,10 +45,16 @@ export function tanstackStart( : ['@tanstack/react-router', '@tanstack/react-router-devtools'], }, optimizeDeps: - environmentName === VITE_ENVIRONMENT_NAMES.client || - (environmentName === VITE_ENVIRONMENT_NAMES.server && - // This indicates that the server environment has opted in to dependency optimization - options.optimizeDeps?.noDiscovery === false) + // Vitest uses Vite's config, but `optimizeDeps` (pre-bundling) causes conflicts + // when workspace packages (transformed by Vitest) interact with external packages (Node-native). + // This is especially problematic for React, leading to "Invalid hook call" errors due to + // duplicate React instances (one pre-bundled ESM, one native CJS). + // We disable this enforced optimization when running in Vitest to allow standard resolution. + process.env.VITEST !== 'true' && + (environmentName === VITE_ENVIRONMENT_NAMES.client || + (environmentName === VITE_ENVIRONMENT_NAMES.server && + // This indicates that the server environment has opted in to dependency optimization + options.optimizeDeps?.noDiscovery === false)) ? { // As `@tanstack/react-start` depends on `@tanstack/react-router`, we should exclude both. exclude: [