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

plugin.ts

338 lines11.7 KB

1import path from 'node:path'
2import { trimPathRight } from '@tanstack/router-core'
3import { VIRTUAL_MODULES } from '@tanstack/start-server-core'
4import { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'
5import * as vite from 'vite'
6import { crawlFrameworkPkgs } from 'vitefu'
7import { join } from 'pathe'
8import { startManifestPlugin } from './start-manifest-plugin/plugin'
9import { startCompilerPlugin } from './start-compiler-plugin/plugin'
10import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from './constants'
11import { tanStackStartRouter } from './start-router-plugin/plugin'
12import { loadEnvPlugin } from './load-env-plugin/plugin'
13import { devServerPlugin } from './dev-server-plugin/plugin'
14import { parseStartConfig } from './schema'
15import { resolveEntry } from './resolve-entries'
16import {
17 getClientOutputDirectory,
18 getServerOutputDirectory,
19} from './output-directory'
20import { postServerBuild } from './post-server-build'
21import { createServerFnPlugin } from './create-server-fn-plugin/plugin'
22import type { ViteEnvironmentNames } from './constants'
23import type {
24 TanStackStartInputConfig,
25 TanStackStartOutputConfig,
26} from './schema'
27import type { PluginOption } from 'vite'
28import type { CompileStartFrameworkOptions } from './start-compiler-plugin/compilers'
29​
30export interface TanStackStartVitePluginCoreOptions {
31 framework: CompileStartFrameworkOptions
32 defaultEntryPaths: {
33 client: string
34 server: string
35 start: string
36 }
38​
39export interface ResolvedStartConfig {
40 root: string
41 startFilePath: string | undefined
42 routerFilePath: string
43 srcDirectory: string
45​
46export type GetConfigFn = () => {
47 startConfig: TanStackStartOutputConfig
48 resolvedStartConfig: ResolvedStartConfig
50export function TanStackStartVitePluginCore(
51 corePluginOpts: TanStackStartVitePluginCoreOptions,
52 startPluginOpts: TanStackStartInputConfig,
53): Array<PluginOption> {
54 const resolvedStartConfig: ResolvedStartConfig = {
55 root: '',
56 startFilePath: undefined,
57 routerFilePath: '',
58 srcDirectory: '',
59 }
60​
61 let startConfig: TanStackStartOutputConfig | null
62 const getConfig: GetConfigFn = () => {
63 if (!resolvedStartConfig.root) {
64 throw new Error(`Cannot get config before root is resolved`)
65 }
66 if (!startConfig) {
67 startConfig = parseStartConfig(
68 startPluginOpts,
69 corePluginOpts,
70 resolvedStartConfig.root,
71 )
72 }
73 return { startConfig, resolvedStartConfig }
74 }
75​
76 const capturedBundle: Partial<
77 Record<ViteEnvironmentNames, vite.Rollup.OutputBundle>
78 > = {}
79​
80 function getBundle(envName: ViteEnvironmentNames): vite.Rollup.OutputBundle {
81 const bundle = capturedBundle[envName]
82 if (!bundle) {
83 throw new Error(`No bundle captured for environment: ${envName}`)
84 }
85 return bundle
86 }
87​
88 return [
89 {
90 name: 'tanstack-start-core:config',
91 enforce: 'pre',
92 async config(viteConfig, { command }) {
93 const viteAppBase = trimPathRight(viteConfig.base || '/')
94 globalThis.TSS_APP_BASE = viteAppBase
95​
96 const root = viteConfig.root || process.cwd()
97 resolvedStartConfig.root = root
98​
99 const { startConfig } = getConfig()
100 const resolvedSrcDirectory = join(root, startConfig.srcDirectory)
101 resolvedStartConfig.srcDirectory = resolvedSrcDirectory
102​
103 const startFilePath = resolveEntry({
104 type: 'start entry',
105 configuredEntry: startConfig.start.entry,
106 defaultEntry: 'start',
107 resolvedSrcDirectory,
108 required: false,
109 })
110 resolvedStartConfig.startFilePath = startFilePath
111​
112 const routerFilePath = resolveEntry({
113 type: 'router entry',
114 configuredEntry: startConfig.router.entry,
115 defaultEntry: 'router',
116 resolvedSrcDirectory,
117 required: true,
118 })
119 resolvedStartConfig.routerFilePath = routerFilePath
120​
121 const clientEntryPath = resolveEntry({
122 type: 'client entry',
123 configuredEntry: startConfig.client.entry,
124 defaultEntry: 'client',
125 resolvedSrcDirectory,
126 required: false,
127 })
128​
129 const serverEntryPath = resolveEntry({
130 type: 'server entry',
131 configuredEntry: startConfig.server.entry,
132 defaultEntry: 'server',
133 resolvedSrcDirectory,
134 required: false,
135 })
136​
137 let clientAlias: string
138 if (clientEntryPath) {
139 clientAlias = vite.normalizePath(
140 path.join('/@fs', path.resolve(root, clientEntryPath)),
141 )
142 } else {
143 clientAlias = corePluginOpts.defaultEntryPaths.client
144 }
145​
146 let serverAlias: string
147 if (serverEntryPath) {
148 serverAlias = vite.normalizePath(path.resolve(root, serverEntryPath))
149 } else {
150 serverAlias = corePluginOpts.defaultEntryPaths.server
151 }
152​
153 let startAlias: string
154 if (startFilePath) {
155 startAlias = vite.normalizePath(path.resolve(root, startFilePath))
156 } else {
157 startAlias = corePluginOpts.defaultEntryPaths.start
158 }
159​
160 const entryAliasConfiguration: Record<
161 (typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS],
162 string
163 > = {
164 [ENTRY_POINTS.start]: startAlias,
165 [ENTRY_POINTS.router]: routerFilePath,
166 [ENTRY_POINTS.client]: clientAlias,
167 [ENTRY_POINTS.server]: serverAlias,
168 }
169​
170 const startPackageName =
171 `@tanstack/${corePluginOpts.framework}-start` as const
172​
173 // crawl packages that have start in "peerDependencies"
174 // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101
175​
176 // this is currently uncached; could be implemented similarly as vite handles lock file changes
177 // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282
178​
179 const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({
180 root: process.cwd(),
181 isBuild: command === 'build',
182 isFrameworkPkgByJson(pkgJson) {
183 const peerDependencies = pkgJson['peerDependencies']
184​
185 if (peerDependencies) {
186 return startPackageName in peerDependencies
187 }
188​
189 return false
190 },
191 })
192​
193 return {
194 base: viteAppBase,
195 // see https://vite.dev/config/shared-options.html#apptype
196 // this will prevent vite from injecting middlewares that we don't want
197 appType: viteConfig.appType ?? 'custom',
198 environments: {
199 [VITE_ENVIRONMENT_NAMES.client]: {
200 consumer: 'client',
201 build: {
202 rollupOptions: {
203 input: {
204 main: ENTRY_POINTS.client,
205 },
206 },
207 outDir: getClientOutputDirectory(viteConfig),
208 },
209 },
210 [VITE_ENVIRONMENT_NAMES.server]: {
211 consumer: 'server',
212​
213 build: {
214 ssr: true,
215 rollupOptions: {
216 input:
217 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
218 ?.build?.rollupOptions?.input ?? ENTRY_POINTS.server,
219 },
220 outDir: getServerOutputDirectory(viteConfig),
221 commonjsOptions: {
222 include: [/node_modules/],
223 },
224 copyPublicDir:
225 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
226 ?.build?.copyPublicDir ?? false,
227 },
228 },
229 },
230​
231 resolve: {
232 noExternal: [
233 // ENTRY_POINTS.start,
234 '@tanstack/start**',
235 `@tanstack/${corePluginOpts.framework}-start**`,
236 ...crawlFrameworkPkgsResult.ssr.noExternal.sort(),
237 ],
238 alias: {
239 ...entryAliasConfiguration,
240 },
241 },
242 /* prettier-ignore */
243 define: {
244 // define is an esbuild function that replaces the any instances of given keys with the given values
245 // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify("TanStack Start")
246 // This is not the same as injecting environment variables.
247​
248 ...defineReplaceEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),
249 ...defineReplaceEnv('TSS_CLIENT_OUTPUT_DIR', getClientOutputDirectory(viteConfig)),
250 ...defineReplaceEnv('TSS_APP_BASE', viteAppBase),
251 ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}),
252 ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'),
253 },
254 builder: {
255 sharedPlugins: true,
256 async buildApp(builder) {
257 const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]
258 const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]
259​
260 if (!client) {
261 throw new Error('Client environment not found')
262 }
263​
264 if (!server) {
265 throw new Error('SSR environment not found')
266 }
267​
268 if (!client.isBuilt) {
269 // Build the client bundle first
270 await builder.build(client)
271 }
272 if (!server.isBuilt) {
273 // Build the SSR bundle
274 await builder.build(server)
275 }
276 const serverBundle = getBundle(VITE_ENVIRONMENT_NAMES.server)
277 await postServerBuild({ builder, startConfig, serverBundle })
278 },
279 },
280 }
281 },
282 },
283 tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts),
284 // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv
285 startCompilerPlugin(corePluginOpts.framework),
286 createServerFnPlugin(corePluginOpts.framework),
287​
288 TanStackServerFnPluginEnv({
289 // This is the ID that will be available to look up and import
290 // our server function manifest and resolve its module
291 manifestVirtualImportId: VIRTUAL_MODULES.serverFnManifest,
292 client: {
293 getRuntimeCode: () =>
294 `import { createClientRpc } from '@tanstack/${corePluginOpts.framework}-start/client'`,
295 replacer: (d) => `createClientRpc('${d.functionId}')`,
296 envName: VITE_ENVIRONMENT_NAMES.client,
297 },
298 server: {
299 getRuntimeCode: () =>
300 `import { createServerRpc } from '@tanstack/${corePluginOpts.framework}-start/server'`,
301 replacer: (d) => `createServerRpc('${d.functionId}', ${d.fn})`,
302 envName: VITE_ENVIRONMENT_NAMES.server,
303 },
304 }),
305 loadEnvPlugin(),
306 startManifestPlugin({
307 getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client),
308 }),
309 devServerPlugin({ getConfig }),
310 {
311 name: 'tanstack-start:core:capture-bundle',
312 applyToEnvironment(e) {
313 return (
314 e.name === VITE_ENVIRONMENT_NAMES.client ||
315 e.name === VITE_ENVIRONMENT_NAMES.server
316 )
317 },
318 enforce: 'post',
319 generateBundle(_options, bundle) {
320 const environment = this.environment.name as ViteEnvironmentNames
321 if (!Object.values(VITE_ENVIRONMENT_NAMES).includes(environment)) {
322 throw new Error(`Unknown environment: ${environment}`)
323 }
324 capturedBundle[environment] = bundle
325 },
326 },
327 ]
329​
330function defineReplaceEnv<TKey extends string, TValue extends string>(
331 key: TKey,
332 value: TValue,
333): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {
334 return {
335 [`process.env.${key}`]: JSON.stringify(value),
336 [`import.meta.env.${key}`]: JSON.stringify(value),
337 } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }