静态服务端函数是在构建时执行,并在使用预渲染/静态生成时缓存为静态资源的服务端函数。通过向createServerFn传递type: 'static'选项,可以将其设置为"静态"模式:
const myServerFn = createServerFn({ type: 'static' }).handler(async () => {
return 'Hello, world!'
})
const myServerFn = createServerFn({ type: 'static' }).handler(async () => {
return 'Hello, world!'
})
该模式的运行流程如下:
默认情况下,静态服务端函数缓存实现通过node的fs模块在构建输出目录中存储和检索静态数据,在运行时同样使用fetch请求相同的静态文件来获取数据。
可以通过导入并调用createServerFnStaticCache函数创建自定义缓存实现,然后调用setServerFnStaticCache进行设置,来自定义该接口:
import {
createServerFnStaticCache,
setServerFnStaticCache,
} from '@tanstack/react-start/client'
const myCustomStaticCache = createServerFnStaticCache({
setItem: async (ctx, data) => {
// 将静态数据存储到自定义缓存中
},
getItem: async (ctx) => {
// 从自定义缓存中检索静态数据
},
fetchItem: async (ctx) => {
// 在运行时从自定义缓存中获取静态数据
},
})
setServerFnStaticCache(myCustomStaticCache)
import {
createServerFnStaticCache,
setServerFnStaticCache,
} from '@tanstack/react-start/client'
const myCustomStaticCache = createServerFnStaticCache({
setItem: async (ctx, data) => {
// 将静态数据存储到自定义缓存中
},
getItem: async (ctx) => {
// 从自定义缓存中检索静态数据
},
fetchItem: async (ctx) => {
// 在运行时从自定义缓存中获取静态数据
},
})
setServerFnStaticCache(myCustomStaticCache)
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.