静态站点生成

在构建时预渲染国际化页面,获得最佳性能

静态站点生成会在构建时预渲染页面,为每个 locale 生成静态 HTML files。这样既能带来出色的性能和 SEO 效益,也能确保用户访问站点时,所有翻译内容立即可用。

要求: SSG 需要 middleware routinglocal translations 才能在国际化场景下正常工作。

应用路由器

设置要求

要在 GT 中启用 SSG,你需要:

  1. 使用带有中间件路由的 App Router - 参见 中间件指南
  2. 本地翻译 - 参见 本地翻译指南
  3. 客户端侧导入 - 使用 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 组件和 hooks 都是从 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';

任何读取请求头或 Cookie 的操作都会阻止静态生成。

[locale] 目录之外的 layout.tsx

如果在 [locale] 目录之外存在 layout.tsx 文件,将会阻止进行静态生成。 你很可能会看到以下错误:

在模块 [next]/root-params.js [app-rsc] (ecmascript) 中未找到导出的 locale。
该模块的所有导出项均为静态已知(不包含动态导出)。因此可以静态确定所请求的导出项不存在。

所有 layout.tsx files 必须位于 [locale] 目录内。 更多信息请参阅相关的 Next.js issue

后续步骤

本指南如何?