# General Translation React SDKs (gt-react, gt-next, gt-react-native): Pages Router 静态站点生成
URL: https://generaltranslation.com/zh/docs/react/nextjs/pages-router-static-site-generation.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何使用 General Translation 预渲染本地化的 Next.js Pages Router 页面。

使用 `withGTStaticProps` 预渲染本地化的 Pages Router 页面。设置方式与 `withGTServerSideProps` 类似，但 Next.js 会在构建时生成这些属性。

## 配置区域设置路由 [#config]

Next.js 必须在构建时获知所有区域设置，才能为每个区域设置生成对应版本的页面。从 `gt.config.json` 导入这些值；其 `locales` 数组必须包含 `defaultLocale`：

```ts title="next.config.ts"
import type { NextConfig } from 'next';
import { withGTConfig } from 'gt-next/config';
import gtConfig from './gt.config.json';

const nextConfig: NextConfig = {
  i18n: {
    locales: gtConfig.locales,
    defaultLocale: gtConfig.defaultLocale,
  },
};

export default withGTConfig(nextConfig);
```

页面保持在原有位置。Next.js 国际化路由会生成本地化 URL，无需使用 `pages/[locale]` 段。完整设置请参阅 [Pages Router 区域设置路由](/docs/react/nextjs/pages-router-middleware)。

## 添加静态属性 [#static-props]

使用 `withGTStaticProps` 包装每个页面的 `getStaticProps` 函数：

```tsx title="pages/about.tsx"
import type { GetStaticProps } from 'next';
import { T, Var, withGTStaticProps } from 'gt-next';

type AboutPageProps = {
  generatedAt: string;
};

export const getStaticProps: GetStaticProps<AboutPageProps> =
  withGTStaticProps(async () => ({
    props: {
      generatedAt: new Date().toISOString(),
    },
  }));

export default function AboutPage({ generatedAt }: AboutPageProps) {
  return <T>Generated at: <Var>{generatedAt}</Var></T>;
}
```

`withGTStaticProps` 会将区域设置和翻译快照添加到返回的页面属性中。如果页面没有其他属性，请使用不带参数的形式：

```tsx title="pages/index.tsx"
import { withGTStaticProps } from 'gt-next';

export const getStaticProps = withGTStaticProps();
```

Next.js 会为每个已配置的区域设置调用一次 `getStaticProps`，并提供 `context.locale`。将生成的值传给 [`GTProvider`](/docs/react/reference/components/gt-provider)，并在 `_app.tsx` 中[接入区域设置变更](/docs/react/nextjs/pages-router-middleware#locale-changes)。

## 处理动态结果 [#dynamic-results]

该包装器会保留 `getStaticProps` 函数返回的 `redirect` 和 `notFound` 结果。仅当结果中包含 `props` 时，才会加载翻译。

```tsx title="pages/products/[id].tsx"
import { withGTStaticProps } from 'gt-next';

export const getStaticProps = withGTStaticProps(async ({ params }) => {
  const product = await loadProduct(params?.id);

  if (!product) {
    return { notFound: true };
  }

  return {
    props: { product },
    revalidate: 3600,
  };
});
```

动态 Pages Router 路由仍需使用 `getStaticPaths`。对于每个要预渲染的区域设置，分别返回一次对应路径：

```tsx title="pages/products/[id].tsx"
import type { GetStaticPaths } from 'next';

export const getStaticPaths: GetStaticPaths = async ({ locales = [] }) => {
  const products = await loadProducts();

  return {
    paths: products.flatMap((product) =>
      locales.map((locale) => ({
        params: { id: product.id },
        locale,
      }))
    ),
    fallback: 'blocking',
  };
};
```

如果路径中未指定 `locale`，Next.js 只会生成该路径的默认区域设置版本。

## 从构建失败中恢复 [#build-failures]

### 无法确定区域设置

当 Next.js 既未提供 `context.locale`，也未提供 `context.defaultLocale` 时，`withGTStaticProps` 会抛出异常。请在 `next.config.ts` 中添加 `i18n.locales` 和 `i18n.defaultLocale`，并确保其与 `gt.config.json` 保持一致。

不要使用 [`createNextMiddleware`](/docs/react/nextjs/reference/functions/create-next-middleware) 替代 Pages Router 的 `i18n` 配置。Middleware 不会提供传递给 `getStaticProps` 的构建时区域设置。

### 默认区域设置显示未翻译内容

默认区域设置会有意接收空的翻译快照，因为页面中已包含源内容。其他区域设置则会加载其生成的翻译快照。

如果目标区域设置也显示源内容，请确认在 `next build` 之前已运行 [`npx gt translate`](/docs/cli/reference/commands/translate)，并且该区域设置同时存在于 Next.js 和 General Translation 的配置中。

### App Router 文件中 helper 抛出异常

`withGTStaticProps` 是 Pages Router 的 API。请在 `app/` 目录下使用 `generateStaticParams` 和 [App Router 静态生成配置](/docs/react/nextjs/app-router-static-site-generation)。

### 静态导出不支持区域设置路由

Next.js Pages Router 的 `i18n` 配置不支持 `output: 'export'`。请通过 Next.js 服务器端或平台适配器部署生成的页面，或迁移到会生成显式 `[locale]` 参数的 App Router 路由。

## Next steps

- /docs/react/nextjs/pages-router-middleware
- /docs/react/guides/storing-translations
- /docs/react/guides/managing-locales
- /docs/react/guides/migrating-i18n-libraries

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
