静态服务器函数

什么是静态服务器函数?

静态服务器函数是在构建时执行的服务器函数,在使用预渲染/静态生成时,它们会作为静态资源被缓存。可以通过向 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)
我们的合作伙伴
Code Rabbit
Netlify
Neon
Clerk
Convex
Sentry
Prisma
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。