靜態伺服器函式 (Static Server Functions) 是在建置時執行並在使用預渲染 (prerendering)/靜態生成 (static-generation) 時快取為靜態資源的伺服器函式。透過將 type: 'static' 選項傳遞給 createServerFn,可將其設定為「靜態」模式:
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.