静态服务器函数

什么是静态服务器函数?

静态服务器函数是在构建时执行并在使用预渲染/静态生成时缓存为静态资源的服务器函数。它们可以通过向 createServerFn 传递 type: 'static' 选项来设置为"静态"模式:

tsx
const myServerFn = createServerFn({ type: 'static' }).handler(async () => {
  return 'Hello, world!'
})
const myServerFn = createServerFn({ type: 'static' }).handler(async () => {
  return 'Hello, world!'
})

此模式的工作流程如下:

  • 构建时
    • 在构建时预渲染期间,执行带有 type: 'static' 的服务器函数
    • 结果与您的构建输出一起缓存为静态 JSON 文件,使用派生键(函数 ID + 参数/负载哈希)
    • 结果在预渲染/静态生成期间正常返回并用于预渲染页面
  • 运行时
    • 最初,提供预渲染页面的 HTML,服务器函数数据嵌入在 HTML 中
    • 当客户端挂载时,嵌入的服务器函数数据被水合
    • 对于未来的客户端调用,服务器函数被替换为对静态 JSON 文件的 fetch 调用

自定义服务器函数静态缓存

默认情况下,静态服务器函数缓存实现通过 node 的 fs 模块在构建输出目录中存储和检索静态数据,并在运行时使用对同一静态文件的 fetch 调用来获取数据。

此接口可以通过导入和调用 createServerFnStaticCache 函数来创建自定义缓存实现,然后调用 setServerFnStaticCache 来设置它:

tsx
import {
  createServerFnStaticCache,
  setServerFnStaticCache,
} from '@tanstack/react-start/client'

const myCustomStaticCache = createServerFnStaticCache({
  setItem: async (ctx, data) => {
    // Store the static data in your custom cache
  },
  getItem: async (ctx) => {
    // Retrieve the static data from your custom cache
  },
  fetchItem: async (ctx) => {
    // During runtime, fetch the static data from your custom cache
  },
})

setServerFnStaticCache(myCustomStaticCache)
import {
  createServerFnStaticCache,
  setServerFnStaticCache,
} from '@tanstack/react-start/client'

const myCustomStaticCache = createServerFnStaticCache({
  setItem: async (ctx, data) => {
    // Store the static data in your custom cache
  },
  getItem: async (ctx) => {
    // Retrieve the static data from your custom cache
  },
  fetchItem: async (ctx) => {
    // During runtime, fetch the static data from your custom cache
  },
})

setServerFnStaticCache(myCustomStaticCache)