静态站点生成
在构建时预渲染国际化页面,获得最佳性能
静态站点生成会在构建时预渲染页面,为每个 locale 生成静态 HTML 文件。这既能提供出色的性能和 SEO 效益,也能确保用户访问你的网站时,所有翻译内容即可用。
要求: 为在国际化场景下正常运行,SSG 需要启用 middleware 路由 和 本地翻译。
App Router(应用路由器)
设置要求
要在 GT 中启用 SSG,你需要:
- 使用带有中间件路由的 App Router - 参见 middleware 指南
- 本地翻译 - 参见 本地翻译指南
- 客户端导入 - 使用 gt-next/client,而不是gt-next
步骤 1:配置 GTProvider
在你的 [locale] 布局中加入 GTProvider,并使用 loadTranslations 函数:
// app/[locale]/layout.tsx
import { GTProvider } from 'gt-next/client';
import { loadTranslations } from '@/loadTranslations';
export default async function RootLayout({ children, params }) {
  const { locale } = await params;
  
  return (
    <GTProvider loadTranslations={loadTranslations} locale={locale}>
      {children}
    </GTProvider>
  );
}步骤 2:使用客户端侧导入
从 gt-next/client 导入所有 GT 组件和 hooks:
// ✅ 使用客户端导入以支持 SSG
import { useGT, T } from 'gt-next/client';
// ❌ 这些会阻止 SSG
import { getGT } from 'gt-next/server';
import { T } from 'gt-next';步骤 3:配置 generateStaticParams
请确保已为你的 locales 配置了 generateStaticParams。
自定义 getLocale
在 SSG 场景下,创建一个适用于静态生成的自定义 getLocale 函数:
Next.js 15.5+
// getLocale.ts
import { locale } from "next/root-params";
export default async function getLocale() {
  return await locale();
}Next.js 15.1–15.4
// getLocale.ts  
import { unstable_rootParams } from "next/server";
export default async function getLocale() {
  return (await unstable_rootParams())?.locale;
}早期版本
很遗憾,在早期版本中,使用 SSG 无法访问 URL 路径参数。你需要升级到 Next.js 15.1 或更高版本。
常见问题
页面未生成静态页面
如果你的页面没有被静态生成,请检查所有 GT 组件和 hook 是否从 gt-next/client 导入:
// ❌ 这些会阻止 SSG
import { getGT } from 'gt-next/server';
import { getLocale } from 'gt-next/server';
import { getTranslations } from 'gt-next/server';
import { T } from 'gt-next';
// ✅ 这些支持 SSG
import { useGT, T } from 'gt-next/client';凡是读取 headers 或 cookies 的操作都会阻止静态生成。
后续步骤
这份指南怎么样?