缓存组件
在 gt-next 中配置缓存组件
Cache Components
本指南介绍如何将 gt-next 与 Next.js 的 Cache Components 配合使用,以优化国际化应用。
配置
如果你还没有这样做,请先按照 Next.js Cache Components 指南 在项目中配置 cache components(缓存组件)。
在 gt-next 配置中启用 cache components 支持:
const nextConfig = {
cacheComponents: true,
};
export default withGTConfig(nextConfig, {
experimentalLocaleResolution: true,
});启用 middleware
在这里查看完整的 middleware 指南。
import { createNextMiddleware } from 'gt-next/middleware';
export default createNextMiddleware();
export const config = {
// 匹配除 API 路由、静态文件和 Next.js 内部路径之外的所有路径
matcher: ['/((?!api|static|.*\\..*|_next).*)']
};为包含可翻译内容的缓存组件添加 locale 参数
在使用包含可翻译内容的缓存组件时,必须将 locale 作为参数传入。这样可以确保每个 locale 拥有各自独立的缓存记录。
import { getLocale } from "gt-next/server"
async function CachedContent({locale}: {locale: string}) {
"use cache"
return <T>Hello World</T>
}
export default async function Page() {
const locale = await getLocale()
return <CachedContent locale={locale} />
}配置说明
- 自定义的
getLocale函数会被重写 getRegion和getDomain函数会被禁用- 可以使用
experimentalLocaleResolutionParam来自定义解析 locale 时使用的参数名称(默认为'locale')
export default withGTConfig(nextConfig, {
experimentalLocaleResolution: true,
experimentalLocaleResolutionParam: 'lang', // 可选自定义
});后续步骤
- 阅读此功能的发布说明 gt-next@6.10.0,以了解更多详情。