Open History to see the last commit
1import { crawlFrameworkPkgs } from 'vitefu'
2import {
3 applyResolvedBaseAndOutput,
4 applyResolvedRouterBasepath,
5 createStartConfigContext,
6} from '../config-context'
7import { START_ENVIRONMENT_NAMES } from '../constants'
8import {
9 createServerFnBasePath,
10 normalizePublicBase,
11 shouldRewriteDevBasepath,
12} from '../planning'
13import { importProtectionPlugin } from './import-protection-plugin/plugin'
14import { startCompilerPlugin } from './start-compiler-plugin/plugin'
15import { loadEnvPlugin } from './load-env-plugin/plugin'
16import {
17 buildStartViteEnvironments,
18 createViteConfigPlan,
19 createViteDefineConfig,
20 createViteResolvedEntryAliases,
21} from './planning'
22import { devServerPlugin } from './dev-server-plugin/plugin'
23import { previewServerPlugin } from './preview-server-plugin/plugin'
24import {
25 createDevBaseRewritePlugin,
26 createDevClientEntryPlugin,
27 createPostBuildPlugin,
28} from './plugins'
29import { parseStartConfig } from './schema'
30import { startManifestPlugin } from './start-manifest-plugin/plugin'
31import { tanStackStartRouter } from './start-router-plugin/plugin'
32import {
33 getClientOutputDirectory,
34 getServerOutputDirectory,
35} from './output-directory'
36import { postServerBuild } from './post-server-build'
37import { serializationAdaptersPlugin } from './serialization-adapters-plugin'
38import type {
39 TanStackStartVitePluginCoreOptions,
40 ViteRscForwardSsrResolverStrategy,
41} from './types'
42import type { TanStackStartViteInputConfig } from './schema'
43import type { PluginOption } from 'vite'
44β
45export function tanStackStartVite(
46 corePluginOpts: TanStackStartVitePluginCoreOptions,
47 startPluginOpts: TanStackStartViteInputConfig | undefined,
48): Array<PluginOption> {
49 const normalizedStartPluginOpts = startPluginOpts ?? {}
50β
51 const configContext = createStartConfigContext({
52 corePluginOpts,
53 startPluginOpts: normalizedStartPluginOpts,
54 parseConfig: parseStartConfig,
55 })
56 const { getConfig, resolvedStartConfig } = configContext
57 const serverFnProviderEnv = corePluginOpts.providerEnvironmentName
58 const ssrIsProvider = corePluginOpts.ssrIsProvider
59β
60 // When the router basepath and vite base are misaligned during dev,
61 // we install a URL rewrite middleware instead of erroring.
62 let needsDevBaseRewrite = false
63β
64 const environments: Array<{
65 name: string
66 type: 'client' | 'server'
67 getServerFnById?: string
68 }> = [
69 { name: START_ENVIRONMENT_NAMES.client, type: 'client' },
70 {
71 name: START_ENVIRONMENT_NAMES.server,
72 type: 'server',
73 getServerFnById:
74 corePluginOpts.ssrResolverStrategy.type === 'vite-rsc-forward'
75 ? createViteRscForwarder(corePluginOpts.ssrResolverStrategy)
76 : undefined,
77 },
78 ]
79 if (
80 serverFnProviderEnv !== START_ENVIRONMENT_NAMES.server &&
81 !environments.find((e) => e.name === serverFnProviderEnv)
82 ) {
83 environments.push({
84 name: serverFnProviderEnv,
85 type: 'server',
86 })
87 }
88 return [
89 {
90 name: 'tanstack-start-core:config',
91 enforce: 'pre',
92 async config(viteConfig, { command }) {
93 const publicBase = normalizePublicBase(viteConfig.base)
94 applyResolvedBaseAndOutput({
95 resolvedStartConfig,
96 root: viteConfig.root || process.cwd(),
97 publicBase,
98 clientOutputDirectory: getClientOutputDirectory(viteConfig),
99 serverOutputDirectory: getServerOutputDirectory(viteConfig),
100 })
101 const { startConfig } = getConfig()
102 const routerBasepath = applyResolvedRouterBasepath({
103 resolvedStartConfig,
104 startConfig,
105 })
106β
107 if (
108 shouldRewriteDevBasepath({
109 command,
110 middlewareMode: Boolean(viteConfig.server?.middlewareMode),
111 routerBasepath,
112 publicBase: resolvedStartConfig.basePaths.publicBase,
113 })
114 ) {
115 // The router basepath and vite base are misaligned.
116 // Instead of erroring, we install a dev-server middleware that
117 // rewrites incoming request URLs to prepend the vite base prefix.
118 // This allows users to have e.g. base: '/_ui/' for asset URLs
119 // while keeping router basepath at '/' for page navigation.
120 needsDevBaseRewrite = true
121 }
122β
123 const TSS_SERVER_FN_BASE = createServerFnBasePath({
124 routerBasepath,
125 serverFnBase: startConfig.serverFns.base,
126 })
127 const resolvedEntryPlan = configContext.resolveEntries()
128β
129 const entryAliases = createViteResolvedEntryAliases({
130 entryPaths: resolvedEntryPlan.entryPaths,
131 })
132β
133 const startPackageName =
134 `@tanstack/${corePluginOpts.framework}-start` as const
135β
136 // crawl packages that have start in "peerDependencies"
137 // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101
138β
139 // this is currently uncached; could be implemented similarly as vite handles lock file changes
140 // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282
141β
142 const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({
143 root: process.cwd(),
144 isBuild: command === 'build',
145 isFrameworkPkgByJson(pkgJson) {
146 const peerDependencies = pkgJson['peerDependencies']
147β
148 if (peerDependencies) {
149 if (
150 startPackageName in peerDependencies ||
151 '@tanstack/start-client-core' in peerDependencies
152 ) {
153 return true
154 }
155 }
156β
157 return false
158 },
159 })
160β
161 const viteConfigPlan = createViteConfigPlan({
162 viteConfig,
163 command,
164 framework: corePluginOpts.framework,
165 entryAliases,
166 clientOutputDirectory: resolvedStartConfig.outputDirectories.client,
167 serverOutputDirectory: resolvedStartConfig.outputDirectories.server,
168 serverFnProviderEnv,
169 optimizeDepsExclude: crawlFrameworkPkgsResult.optimizeDeps.exclude,
170 noExternal: crawlFrameworkPkgsResult.ssr.noExternal.sort(),
171 })
172β
173 return {
174 // see https://vite.dev/config/shared-options.html#apptype
175 // this will prevent vite from injecting middlewares that we don't want
176 appType: viteConfig.appType ?? 'custom',
177 environments: viteConfigPlan.environments,
178 resolve: viteConfigPlan.resolve,
179 define: createViteDefineConfig({
180 command,
181 mode: viteConfig.mode,
182 serverFnBase: TSS_SERVER_FN_BASE,
183 routerBasepath,
184 spaEnabled: startConfig.spa?.enabled,
185 devSsrStylesEnabled: startConfig.dev.ssrStyles.enabled,
186 devSsrStylesBasepath:
187 startConfig.dev.ssrStyles.basepath ??
188 resolvedStartConfig.basePaths.publicBase,
189 inlineCssEnabled:
190 command === 'build' && startConfig.server.build.inlineCss.enabled,
191 staticNodeEnv: startConfig.server.build.staticNodeEnv,
192 disableCsrfMiddlewareWarning:
193 startConfig.serverFns.disableCsrfMiddlewareWarning,
194 }),
195 builder: {
196 sharedPlugins: true,
197 async buildApp(builder) {
198 await buildStartViteEnvironments({
199 builder,
200 providerEnvironmentName: serverFnProviderEnv,
201 ssrIsProvider,
202 })
203 },
204 },
205 }
206 },
207 },
208 createPostBuildPlugin({
209 getConfig,
210 postServerBuild,
211 }),
212 // Server function plugin handles:
213 // 1. Identifying createServerFn().handler() calls
214 // 2. Extracting server functions to separate modules
215 // 3. Replacing call sites with RPC stubs
216 // 4. Generating the server function manifest
217 // Also handles createIsomorphicFn, createServerOnlyFn, createClientOnlyFn, createMiddleware
218 startCompilerPlugin({
219 framework: corePluginOpts.framework,
220 environments,
221 generateFunctionId:
222 normalizedStartPluginOpts.serverFns?.generateFunctionId,
223 compilerTransforms: corePluginOpts.compilerTransforms,
224 serverFnProviderModuleDirectives:
225 corePluginOpts.serverFnProviderModuleDirectives,
226 providerEnvName: serverFnProviderEnv,
227 }),
228 importProtectionPlugin({
229 getConfig,
230 framework: corePluginOpts.framework,
231 environments,
232 providerEnvName: serverFnProviderEnv,
233 }),
234 tanStackStartRouter(normalizedStartPluginOpts, getConfig, corePluginOpts),
235 loadEnvPlugin(),
236 createDevClientEntryPlugin({
237 framework: corePluginOpts.framework,
238 getClientEntry: () => configContext.resolveEntries().entryPaths.client,
239 }),
240 startManifestPlugin({
241 getConfig,
242 }),
243 // When the vite base and router basepath are misaligned (e.g. base: '/_ui/', basepath: '/'),
244 // install a middleware that rewrites incoming request URLs to prepend the vite base prefix.
245 // This allows Vite's internal base middleware to accept the requests, then strips the prefix
246 // before passing to the SSR handler.
247 // Registered BEFORE devServerPlugin so this middleware is added to the Connect stack first,
248 // ensuring all subsequent middlewares (CSS, SSR, etc.) see the rewritten URL.
249 createDevBaseRewritePlugin({
250 shouldRewriteDevBase: () => needsDevBaseRewrite,
251 resolvedStartConfig,
252 }),
253 devServerPlugin({
254 getConfig,
255 devSsrStylesEnabled:
256 normalizedStartPluginOpts.dev?.ssrStyles?.enabled ?? true,
257 installDevServerMiddleware:
258 normalizedStartPluginOpts.vite?.installDevServerMiddleware,
259 }),
260 previewServerPlugin(),
261 ...(corePluginOpts.serializationAdapters?.length
262 ? [
263 serializationAdaptersPlugin({
264 adapters: corePluginOpts.serializationAdapters,
265 }),
266 ]
267 : []),
268 ]
269}
270β
271function createViteRscForwarder(strategy: ViteRscForwardSsrResolverStrategy) {
272 return `export async function getServerFnById(id, access) {
273 const m = await import.meta.viteRsc.loadModule(${JSON.stringify(strategy.sourceEnvironmentName)}, ${JSON.stringify(strategy.sourceEntry)})
274 return m[${JSON.stringify(strategy.exportName)}](id, access)
275}`
276}