Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

vite.ts

238 lines8.5 KB

1import { fileURLToPath } from 'node:url'
2import path from 'pathe'
3import { createVirtualModule } from '@tanstack/start-plugin-core/vite'
4import { createRscCssCompilerTransforms } from './rscCssTransform'
5import type {
6 TanStackStartVitePluginCoreOptions,
7 ViteRscForwardSsrResolverStrategy,
8} from '@tanstack/start-plugin-core/vite'
9import type { PluginOption, UserConfig } from 'vite'
10​
11const isClientEnvironment = (env: { config: { consumer: string } }) =>
12 env.config.consumer === 'client'
13​
14// Virtual module ids used by the React Start RSC runtime.
15const RSC_HMR_VIRTUAL_ID = 'virtual:tanstack-rsc-hmr'
16const RSC_RUNTIME_VIRTUAL_ID = 'virtual:tanstack-rsc-runtime'
17const RSC_BROWSER_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-browser-decode'
18const RSC_SSR_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-ssr-decode'
19const RSC_ENV_NAME = 'rsc'
20​
21const currentDir = path.dirname(fileURLToPath(import.meta.url))
22const entryDir = path.resolve(currentDir, '..', '..', 'plugin', 'entry')
23const rscEntryPath = path.resolve(entryDir, 'rsc.tsx')
24​
25export function configureRsc(): {
26 envName: string
27 providerEnvironmentName: TanStackStartVitePluginCoreOptions['providerEnvironmentName']
28 ssrResolverStrategy: TanStackStartVitePluginCoreOptions['ssrResolverStrategy']
29 serializationAdapters: TanStackStartVitePluginCoreOptions['serializationAdapters']
30 compilerTransforms: TanStackStartVitePluginCoreOptions['compilerTransforms']
31} {
32 const serializationAdapters: TanStackStartVitePluginCoreOptions['serializationAdapters'] =
33 [
34 // IMPORTANT: plugin-adapters-plugin only calls the top-level factory once.
35 // That factory must return a flat array of adapters (not nested arrays),
36 // otherwise router-core ends up with non-adapter entries and Seroval crashes.
37 {
38 client: {
39 module: '@tanstack/react-start/rsc/serialization/client',
40 export: 'rscSerializationAdapter',
41 isFactory: true,
42 },
43 server: {
44 module: '@tanstack/react-start/rsc/serialization/server',
45 export: 'rscSerializationAdapter',
46 isFactory: true,
47 },
48 },
49 ]
50 const ssrResolverStrategy = {
51 type: 'vite-rsc-forward',
52 sourceEnvironmentName: RSC_ENV_NAME,
53 sourceEntry: 'index',
54 exportName: 'getServerFnById',
55 } satisfies ViteRscForwardSsrResolverStrategy
56 return {
57 envName: RSC_ENV_NAME,
58 providerEnvironmentName: RSC_ENV_NAME,
59 ssrResolverStrategy,
60 serializationAdapters,
61 compilerTransforms: createRscCssCompilerTransforms({
62 loadCssExpression: 'import.meta.viteRsc.loadCss()',
63 }),
64 }
66export function reactStartRscVitePlugin(): PluginOption {
67 return [
68 // When RSC is enabled, SSR needs noExternal: true to ensure single React instance.
69 // The RSC decoder's dynamic imports for client components can cause module duplication
70 // without this, leading to "Invalid hook call" errors.
71 // We use the top-level `ssr` config option as `environments.ssr.resolve.noExternal`
72 // doesn't have the same effect.
73 {
74 name: 'tanstack-react-start:rsc-ssr-config',
75 config() {
76 return {
77 ssr: {
78 noExternal: true,
79 },
80 }
81 },
82 },
83 {
84 name: 'tanstack-react-start:rsc-env-config',
85 config() {
86 return {
87 rsc: {
88 // Disable @vitejs/plugin-rsc's built-in server handler middleware.
89 // TanStack Start has its own request handling via the SSR environment.
90 serverHandler: false,
91 // Disable CSS link precedence to prevent React 19 SSR suspension
92 // TanStack Start handles CSS preloading via manifest injection instead
93 cssLinkPrecedence: false,
94 },
95 environments: {
96 [RSC_ENV_NAME]: {
97 consumer: 'server',
98 // Force @tanstack packages to be processed by Vite as source code
99 // rather than treated as external modules. This ensures:
100 // 1. createIsomorphicFn transforms are applied
101 // 2. Imports are resolved within the RSC environment context
102 // with proper react-server conditions and pre-bundled deps
103 resolve: {
104 noExternal: [
105 '@tanstack/start**',
106 '@tanstack/react-start',
107 '@tanstack/react-start-rsc',
108 '@tanstack/react-router',
109 ],
110 },
111 build: {
112 rolldownOptions: {
113 input: {
114 index: rscEntryPath,
115 },
116 },
117 },
118 },
119 },
120 } satisfies UserConfig & {
121 rsc: {
122 serverHandler: false
123 cssLinkPrecedence?: boolean
124 }
125 }
126 },
127 },
128​
129 {
130 name: 'tanstack-react-start:rsc-scan-virtual-fallback',
131 apply: 'build',
132 applyToEnvironment(env) {
133 return env.name === RSC_ENV_NAME
134 },
135 load: {
136 filter: {
137 id: /^(virtual:tanstack-rsc-runtime|virtual:vite-rsc\/encryption-key)$/,
138 },
139 handler(id) {
140 if (this.environment.config.build.write !== false) return
141​
142 if (id === RSC_RUNTIME_VIRTUAL_ID) {
143 return `export { renderToReadableStream, createFromReadableStream, createTemporaryReferenceSet, decodeReply, loadServerAction, decodeAction, decodeFormState } from '@vitejs/plugin-rsc/rsc'`
144 }
145​
146 if (id === 'virtual:vite-rsc/encryption-key') {
147 return `export default () => ''`
148 }
149​
150 return undefined
151 },
152 },
153 },
154​
155 // Runtime bridge into the Vite RSC environment.
156 createVirtualModule({
157 name: 'tanstack-react-start:rsc-runtime-virtual',
158 moduleId: RSC_RUNTIME_VIRTUAL_ID,
159 load() {
160 const envName = this.environment.name
161 if (envName === RSC_ENV_NAME) {
162 return `export { renderToReadableStream, createFromReadableStream, createTemporaryReferenceSet, decodeReply, loadServerAction, decodeAction, decodeFormState } from '@vitejs/plugin-rsc/rsc'`
163 }
164 return `
165export function renderToReadableStream() { throw new Error('renderToReadableStream can only be used in RSC environment'); }
166export function createFromReadableStream() { throw new Error('createFromReadableStream can only be used in RSC environment'); }
167export function createTemporaryReferenceSet() { throw new Error('createTemporaryReferenceSet can only be used in RSC environment'); }
168export function decodeReply() { throw new Error('decodeReply can only be used in RSC environment'); }
169export function loadServerAction() { throw new Error('loadServerAction can only be used in RSC environment'); }
170export function decodeAction() { throw new Error('decodeAction can only be used in RSC environment'); }
171export function decodeFormState() { throw new Error('decodeFormState can only be used in RSC environment'); }
173 },
174 }),
175 createVirtualModule({
176 name: 'tanstack-react-start:rsc-browser-decode-virtual',
177 moduleId: RSC_BROWSER_DECODE_VIRTUAL_ID,
178 load() {
179 return `export { createFromReadableStream, createFromFetch } from '@vitejs/plugin-rsc/browser'`
180 },
181 }),
182 createVirtualModule({
183 name: 'tanstack-react-start:rsc-ssr-decode-virtual',
184 moduleId: RSC_SSR_DECODE_VIRTUAL_ID,
185 load() {
186 return `export { setOnClientReference, createFromReadableStream } from '@vitejs/plugin-rsc/ssr'`
187 },
188 }),
189 createVirtualModule({
190 name: 'tanstack-react-start:rsc-hmr-virtual:dev',
191 moduleId: RSC_HMR_VIRTUAL_ID,
192 apply: 'serve',
193 applyToEnvironment: isClientEnvironment,
194 load() {
195 return `
196export function setupRscHmr() {
197if (!import.meta.hot) {
198 return
200​
201 let __invalidateQueued = false
202​
203 function __queueInvalidate() {
204 if (__invalidateQueued) return
205 __invalidateQueued = true
206 queueMicrotask(async () => {
207 __invalidateQueued = false
208 try {
209 const router = window.__TSR_ROUTER__
210 if (!router) {
211 console.warn('[rsc:hmr] No router found on window.__TSR_ROUTER__')
212 return
213 }
214 await router.invalidate()
215 } catch (e) {
216 console.warn('[rsc:hmr] Failed to invalidate router:', e)
217 }
218 })
219 }
220​
221 import.meta.hot.on('rsc:update', () => {
222 __queueInvalidate()
223 })
226 },
227 }),
228 createVirtualModule({
229 name: 'tanstack-react-start:rsc-hmr-virtual:prod',
230 moduleId: RSC_HMR_VIRTUAL_ID,
231 applyToEnvironment: isClientEnvironment,
232 apply: 'build',
233 load() {
234 return 'export function setupRscHmr() {} '
235 },
236 }),
237 ]