gt-next@6.10.0
概述
gt-next 6.10.0 引入了对缓存组件的实验性支持,同时弃用了 gt-next@6.9 中的旧版静态请求函数。
- 通过
experimentalLocaleResolution新增实验性的缓存组件支持 - 弃用了
gt-next@6.9中的旧版静态请求函数
缓存组件
要启用缓存组件支持,请在 gt-next 配置中添加 experimentalLocaleResolution: true,并按照 Next.js Cache Components 指南 进行配置。将缓存组件用于可翻译内容时,你必须把 locale 作为参数传入,以确保在不同区域设置下都能正确触发缓存失效。
考虑以下应用程序结构:
import { Suspense } from "react";
import { getLocale, getLocales } from "gt-next/server";
export const generateStaticParams = () => {
return getLocales().map(locale => ({ locale }))
}
async function CachedContent({locale: _locale}: {locale: string}) {
"use cache"
return (
<div>
<T><h1>Cached Content</h1></T>
</div>
)
}
export default async function Home() {
const locale = await getLocale()
return (
<div>
<CachedContent locale={locale} />
</div>
);
}locale 参数要求
缓存组件会将其参数用作缓存键。因此,任何包含可翻译内容的缓存组件都必须接收 locale 参数,才能在用户的区域设置变更时更新。例如,CachedContent 必须接收 locale 参数,才能为每个区域设置创建独立的缓存条目。否则,无论用户的区域设置是什么,该组件都会返回相同的缓存内容。
配置说明
启用 experimentalLocaleResolution 时:
- 必须启用 I18n Proxy,区域设置解析才能正常工作 (参见 I18n Proxy)
- 它会覆盖所有自定义的
getLocale函数 (区域设置解析会通过读取 URL 路径进行) - 它会禁用
getRegion和getDomain函数 - 它与已弃用的
experimentalEnableSSG配置冲突——同一时间只能启用一个 - 你可以使用
experimentalLocaleResolutionParam自定义区域设置参数名 (默认为'locale')
export default withGTConfig(nextConfig, {
experimentalLocaleResolution: true,
// 可选:自定义参数名称
experimentalLocaleResolutionParam: 'lang',
})弃用旧版静态请求函数
自 gt-next@6.9 引入静态渲染支持后,我们现开始弃用旧版静态请求函数 (getStaticLocale、getStaticRegion、getStaticDomain) ,并改用标准请求函数 (getLocale、getRegion、getDomain) 。
此次弃用符合我们简化 API 表面的目标,同时保留了完整功能。旧版静态函数仍可继续使用,但会发出弃用警告。为保持一致性,我们建议迁移到标准请求函数。
迁移指南
旧版 SSG
替换已弃用的静态请求函数:
// 之前(已弃用)
export default withGTConfig(nextConfig, {
experimentalEnableSSG: true,
})
// 之后
export default withGTConfig(nextConfig, {
// 默认启用
})移除所有自定义 getStaticLocale、getStaticRegion 或 getStaticDomain 函数,改为使用自定义 getLocale、getRegion 或 getDomain 函数。你必须添加一个自定义 getLocale 函数,并禁用 getRegion 函数。有关更多信息,请参阅 SSG 指南。
import { locale } from "next/root-params";
export default async function getLocale() {
return await locale();
}export default async function getRegion() {
return undefined;
}对于缓存组件
启用实验性的区域设置解析,并确保向缓存组件传递区域设置参数:
const nextConfig = {
cacheComponents: true,
}
// 配置
export default withGTConfig(nextConfig, {
experimentalLocaleResolution: true,
})// 组件实现
async function MyCachedComponent({locale}: {locale: string}) {
"use cache"
// 在此处添加国际化内容
return <T>Content for <Var>{locale}</Var></T>
}
// 用法
export default async function Page() {
const locale = await getLocale()
return <MyCachedComponent locale={locale} />
}