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

plugin.ts

339 lines12.1 KB

1import { trimPathRight } from '@tanstack/router-core'
2import { VIRTUAL_MODULES } from '@tanstack/start-server-core'
3import { TanStackServerFnPluginEnv } from '@tanstack/server-functions-plugin'
4import * as vite from 'vite'
5import { crawlFrameworkPkgs } from 'vitefu'
6import { join } from 'pathe'
7import { escapePath } from 'tinyglobby'
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 const clientAlias = vite.normalizePath(
138 clientEntryPath ?? corePluginOpts.defaultEntryPaths.client,
139 )
140 const serverAlias = vite.normalizePath(
141 serverEntryPath ?? corePluginOpts.defaultEntryPaths.server,
142 )
143 const startAlias = vite.normalizePath(
144 startFilePath ?? corePluginOpts.defaultEntryPaths.start,
145 )
146 const routerAlias = vite.normalizePath(routerFilePath)
147​
148 const entryAliasConfiguration: Record<
149 (typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS],
150 string
151 > = {
152 [ENTRY_POINTS.client]: clientAlias,
153 [ENTRY_POINTS.server]: serverAlias,
154 [ENTRY_POINTS.start]: startAlias,
155 [ENTRY_POINTS.router]: routerAlias,
156 }
157​
158 const startPackageName =
159 `@tanstack/${corePluginOpts.framework}-start` as const
160​
161 // crawl packages that have start in "peerDependencies"
162 // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101
163​
164 // this is currently uncached; could be implemented similarly as vite handles lock file changes
165 // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282
166​
167 const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({
168 root: process.cwd(),
169 isBuild: command === 'build',
170 isFrameworkPkgByJson(pkgJson) {
171 const peerDependencies = pkgJson['peerDependencies']
172​
173 if (peerDependencies) {
174 return startPackageName in peerDependencies
175 }
176​
177 return false
178 },
179 })
180​
181 return {
182 base: viteAppBase,
183 // see https://vite.dev/config/shared-options.html#apptype
184 // this will prevent vite from injecting middlewares that we don't want
185 appType: viteConfig.appType ?? 'custom',
186 environments: {
187 [VITE_ENVIRONMENT_NAMES.client]: {
188 consumer: 'client',
189 build: {
190 rollupOptions: {
191 input: {
192 main: ENTRY_POINTS.client,
193 },
194 },
195 outDir: getClientOutputDirectory(viteConfig),
196 },
197 optimizeDeps: {
198 // Ensure user code can be crawled for dependencies
199 entries: [clientAlias, routerAlias].map((entry) =>
200 // Entries are treated as `tinyglobby` patterns so need to be escaped
201 escapePath(entry),
202 ),
203 },
204 },
205 [VITE_ENVIRONMENT_NAMES.server]: {
206 consumer: 'server',
207 build: {
208 ssr: true,
209 rollupOptions: {
210 input:
211 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
212 ?.build?.rollupOptions?.input ?? ENTRY_POINTS.server,
213 },
214 outDir: getServerOutputDirectory(viteConfig),
215 commonjsOptions: {
216 include: [/node_modules/],
217 },
218 copyPublicDir:
219 viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server]
220 ?.build?.copyPublicDir ?? false,
221 },
222 optimizeDeps: {
223 // Ensure user code can be crawled for dependencies
224 entries: [serverAlias, startAlias, routerAlias].map((entry) =>
225 // Entries are treated as `tinyglobby` patterns so need to be escaped
226 escapePath(entry),
227 ),
228 },
229 },
230 },
231​
232 resolve: {
233 noExternal: [
234 // ENTRY_POINTS.start,
235 '@tanstack/start**',
236 `@tanstack/${corePluginOpts.framework}-start**`,
237 ...crawlFrameworkPkgsResult.ssr.noExternal.sort(),
238 ],
239 alias: {
240 ...entryAliasConfiguration,
241 },
242 },
243 /* prettier-ignore */
244 define: {
245 // define is an esbuild function that replaces the any instances of given keys with the given values
246 // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify("TanStack Start")
247 // This is not the same as injecting environment variables.
248​
249 ...defineReplaceEnv('TSS_SERVER_FN_BASE', startConfig.serverFns.base),
250 ...defineReplaceEnv('TSS_CLIENT_OUTPUT_DIR', getClientOutputDirectory(viteConfig)),
251 ...defineReplaceEnv('TSS_APP_BASE', viteAppBase),
252 ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}),
253 ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'),
254 },
255 builder: {
256 sharedPlugins: true,
257 async buildApp(builder) {
258 const client = builder.environments[VITE_ENVIRONMENT_NAMES.client]
259 const server = builder.environments[VITE_ENVIRONMENT_NAMES.server]
260​
261 if (!client) {
262 throw new Error('Client environment not found')
263 }
264​
265 if (!server) {
266 throw new Error('SSR environment not found')
267 }
268​
269 if (!client.isBuilt) {
270 // Build the client bundle first
271 await builder.build(client)
272 }
273 if (!server.isBuilt) {
274 // Build the SSR bundle
275 await builder.build(server)
276 }
277 const serverBundle = getBundle(VITE_ENVIRONMENT_NAMES.server)
278 await postServerBuild({ builder, startConfig, serverBundle })
279 },
280 },
281 }
282 },
283 },
284 tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts),
285 // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPluginEnv
286 startCompilerPlugin(corePluginOpts.framework),
287 createServerFnPlugin(corePluginOpts.framework),
288​
289 TanStackServerFnPluginEnv({
290 // This is the ID that will be available to look up and import
291 // our server function manifest and resolve its module
292 manifestVirtualImportId: VIRTUAL_MODULES.serverFnManifest,
293 client: {
294 getRuntimeCode: () =>
295 `import { createClientRpc } from '@tanstack/${corePluginOpts.framework}-start/client-rpc'`,
296 replacer: (d) => `createClientRpc('${d.functionId}')`,
297 envName: VITE_ENVIRONMENT_NAMES.client,
298 },
299 server: {
300 getRuntimeCode: () =>
301 `import { createServerRpc } from '@tanstack/${corePluginOpts.framework}-start/server-rpc'`,
302 replacer: (d) => `createServerRpc('${d.functionId}', ${d.fn})`,
303 envName: VITE_ENVIRONMENT_NAMES.server,
304 },
305 }),
306 loadEnvPlugin(),
307 startManifestPlugin({
308 getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client),
309 }),
310 devServerPlugin({ getConfig }),
311 {
312 name: 'tanstack-start:core:capture-bundle',
313 applyToEnvironment(e) {
314 return (
315 e.name === VITE_ENVIRONMENT_NAMES.client ||
316 e.name === VITE_ENVIRONMENT_NAMES.server
317 )
318 },
319 enforce: 'post',
320 generateBundle(_options, bundle) {
321 const environment = this.environment.name as ViteEnvironmentNames
322 if (!Object.values(VITE_ENVIRONMENT_NAMES).includes(environment)) {
323 throw new Error(`Unknown environment: ${environment}`)
324 }
325 capturedBundle[environment] = bundle
326 },
327 },
328 ]
330​
331function defineReplaceEnv<TKey extends string, TValue extends string>(
332 key: TKey,
333 value: TValue,
334): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } {
335 return {
336 [`process.env.${key}`]: JSON.stringify(value),
337 [`import.meta.env.${key}`]: JSON.stringify(value),
338 } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue }