渲染
静态预渲染(Static Prerendering / SSG)
静态预渲染(Static Prerendering)是为你的应用生成静态 HTML 文件的过程。它既可以用来提升应用性能(把预渲染好的 HTML 文件提供给用户,而不必实时生成),也可以用来把静态站点部署到不支持服务端渲染的平台上。
预渲染
TanStack Start 可以把你的应用预渲染成静态 HTML 文件,之后无需实时生成即可提供给用户。要预渲染你的应用,在 tanstackStart 配置中添加 prerender 选项:
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
tanstackStart({
prerender: {
// Switch to true to enable prerendering
enabled: false,
// Disable if you need pages to be at `/page.html` instead of `/page/index.html`
autoSubfolderIndex: true,
// If disabled, only the root path or the paths defined in the pages config will be prerendered
autoStaticPathsDiscovery: true,
// How many prerender jobs to run at once
concurrency: 14,
// Whether to extract links from the HTML and prerender them also
crawlLinks: true,
// Filter function takes the page object and returns whether it should prerender
filter: ({ path }) => !path.startsWith('/do-not-render-me'),
// Number of times to retry a failed prerender job
retryCount: 2,
// Delay between retries in milliseconds
retryDelay: 1000,
// Maximum number of redirects to follow during prerendering
maxRedirects: 5,
// Fail if an error occurs during prerendering
failOnError: true,
// Callback when page is successfully rendered
onSuccess: ({ page }) => {
console.log(`Rendered ${page.path}!`)
},
},
// Optional configuration for specific pages
// Note: When autoStaticPathsDiscovery is enabled (default), discovered static
// routes will be merged with the pages specified below
pages: [
{
path: '/my-page',
prerender: { enabled: true, outputPath: '/my-page/index.html' },
},
],
}),
viteReact(),
],
})译者注:SSG 与其他渲染方式的关系
静态预渲染(SSG)是在构建时把页面渲染成静态 HTML,与 SSR(每次请求实时渲染)、ISR(静态 + 定期/按需重建)并列为几种渲染策略。SSG 的页面最快、最省钱(纯 CDN 托管),但内容更新需要重新构建。ISR 则兼顾两者:静态页面按 Cache-Control 头定期或按需重新生成。
自动静态路由发现
所有静态路径都会被自动发现,并与指定的 pages 配置无缝合并。
以下情况的路由会被排除在自动发现之外:
- 带路径参数的路由(如
/users/$userId),因为它们需要具体的参数值 - 布局路由(以
_前缀开头),因为它们不渲染独立页面 - 没有组件的路由(例如 API 路由)
注意:启用 crawlLinks 时,动态路由如果被其他页面链接,仍然可以被预渲染。
爬取链接
启用 crawlLinks(默认:true)后,TanStack Start 会从预渲染页面中提取链接,并把链接到的页面也一并预渲染。
例如,如果 / 包含一个指向 /posts 的链接,那么 /posts 也会被自动预渲染。