next-i18next 静态国际化实战:pages-router-ssg 全静态站点示例深度解析

原创2026-10-14 12:26:061,383 阅读
文章标签:前端后端

next-i18next 静态国际化实战:pages-router-ssg 全静态站点示例深度解析

导读

本文以仓库中的 pages-router-ssg 示例 为主线,讲解如何用 next-i18next 与 next-language-detector 构建一个**完全静态(SSG/静态导出)**的多语言 Next.js 站点:从 next.config.js 的 output: 'export'、动态路由 [locale] 的 getStaticPaths/getStaticProps、服务端翻译资源注入,到客户端语言检测重定向、语言切换组件与静态 404 页面。读完本文,你将掌握一套可直接复制到生产环境的「静态导出 + 前端国际化」完整方案,并理解其背后 serverSideTranslations 与 appWithTranslation 的底层工作原理。


一、示例定位:什么是 pages-router-ssg

pages-router-ssg 是 next-i18next 仓库中的一个示例工程(Pages Router 体系),其核心目标正如 README 所述:

这是一个展示如何将 next-i18next 与 Next.js 结合、构建完整静态网站的简单示例,并可选使用 Locize 来快速、轻松地获取翻译。

它同时依赖两个库:

  • next-i18next:为 Next.js 提供 SSR/SSG 翻译能力与页面级配置;
  • next-language-detector:在客户端探测用户语言并自动重定向到对应的 /[locale] 页面。

示例内置了 en / de / it 三种语言,翻译资源存放在 public/locales 下,最终通过 next build 导出为纯静态的 out 目录,可部署到任意静态托管服务(如 GitHub Pages)——这正是 README 中「You can now deploy the out folder to any static webserver」所指的场景。

示例的关键入口文件结构如下:

examples/pages-router-ssg/
├── next-i18next.config.js      # 国际化配置(语言列表、默认语言)
├── next.config.js              # output: 'export' + trailingSlash
├── package.json                # 构建/导出/本地预览脚本
├── lib/
│   ├── getStatic.js            # SSG 辅助:getStaticPaths / makeStaticProps
│   ├── languageDetector.js     # 基于 next-language-detector 的语言检测
│   └── redirect.js             # 客户端语言检测重定向逻辑
├── components/
│   ├── Header.js / Footer.js   # 页面骨架与语言切换入口
│   ├── Link.js                 # 自动拼接 locale 前缀的链接
│   └── LanguageSwitchLink.js   # 语言切换按钮
├── pages/
│   ├── _app.js                 # appWithTranslation 包裹
│   ├── _document.js            # 按 locale 设置 <html lang>
│   ├── index.js / second-page.js / 404.js   # 语言检测重定向页
│   └── [locale]/               # 真正的国际化页面
│       ├── index.js
│       ├── second-page.js
│       └── 404.js
└── public/locales/{en,de,it}/*.json

二、快速验证:从拉取到本地跑通

README 给出了最直接的验证步骤:把示例拉到本地后依次执行:

npm i
npm run build
npm run serve

然后打开浏览器访问 http://localhost:8080,即可看到带语言检测重定向的多语言静态站点。

这些命令的实际定义在 package.json 中,各脚本用途如下:

脚本 命令 作用
dev next dev 开发模式(默认 npm start 即此命令)
build next build 构建并执行静态导出
postbuild npm run 404 构建后自动执行 404 处理
404 cp out/404/index.html out/404.html 把 [locale] 静态 404 页面复制为根级 out/404.html
serve http-server out -p 8080 用 http-server 在 8080 端口本地预览 out 目录
server next start 若改用 SSR 模式则启动 Next.js 服务
downloadLocales locize download ... 从 Locize 拉取翻译到 public/locales(可选)
clean rimraf .next out 清理构建产物

关于 npm run build 有一个值得注意的细节:Next.js 的静态导出(output: 'export')不会生成 404 页面,因此示例通过 postbuild 钩子执行 cp out/404/index.html out/404.html,把 [locale]/404 生成的静态页面手动复制为根级 404 页面,确保部署后访问任意不存在路径都能返回本地化的 404。


三、静态化与国际化配置:两份核心配置文件

3.1 next-i18next.config.js:语言配置

examples/pages-router-ssg/next-i18next.config.js:

module.exports = {
  debug: process.env.NODE_ENV === 'development',
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'de', 'it'],
  },
}
  • i18n.defaultLocale:默认语言,这里为 en。它同时被语言检测器用作 fallback。
  • i18n.locales:站点支持的语言集合 ['en', 'de', 'it'],getStaticPaths 会据此为每种语言生成静态页面。
  • debug:仅在开发环境开启 i18next 调试日志,避免生产环境输出冗余信息。

该配置文件同时被服务端(serverSideTranslations)和客户端(appWithTranslation)两侧读取,是整个国际化的单一事实来源。仓库根目录的 src/pagesRouter/config/defaultConfig.ts 展示了更多可用的默认配置项(如 localePath: './public/locales'、localeStructure: '{{lng}}/{{ns}}'、localeExtension: 'json'、load: 'currentOnly'、react.useSuspense: false、serializeConfig: true 等),本例只显式覆盖了语言与 debug 两项,其余均取默认值。

3.2 next.config.js:开启静态导出

examples/pages-router-ssg/next.config.js:

module.exports = {
  output: 'export',
  trailingSlash: true,
}
  • output: 'export':让 next build 输出纯静态的 out 目录,这是整个示例「静态化」的开关。注意代码中 i18n 配置被注释掉了——因为 next-i18next 在静态导出模式下不依赖 Next.js 内置的 locale 路由,而是通过 [locale] 动态路由 + getStaticPaths 自行生成各语言页面。
  • trailingSlash: true:为导出的 HTML 生成目录形式的 URL(如 /de/),方便静态托管服务直接定位 de/index.html。

四、国际化页面骨架:[locale] 动态路由 + SSG

4.1 _app.js:注入翻译运行时

examples/pages-router-ssg/pages/_app.js 只有几行:

import { appWithTranslation } from 'next-i18next/pages'

const MyApp = ({ Component, pageProps }) => (
  <Component {...pageProps} />
)

export default appWithTranslation(MyApp)

appWithTranslation 是 next-i18next 在 Pages Router 下的核心 HOC。其实现位于 src/pagesRouter/appWithTranslation.tsx:

  • 从 pageProps._nextI18Next 读取服务端注入的 initialI18nStore、initialLocale、ns 与 userConfig;
  • 在浏览器端基于这些数据创建(或复用)i18next 实例,并通过 addResourceBundle 把服务端资源合并进实例;
  • 通过 useIsomorphicLayoutEffect 调用 changeLanguage(locale) 完成语言切换;
  • 最终用 <I18nextProvider> 包裹应用,向 useTranslation 等 Hook 提供翻译能力。

4.2 页面与 getStaticPaths / getStaticProps

真正的多语言首页位于 pages/[locale]/index.js:

import { useTranslation } from 'next-i18next/pages'
import { getStaticPaths, makeStaticProps } from '../../lib/getStatic'

const Homepage = () => {
  const { t } = useTranslation(['common', 'footer'])
  return (
    <>
      <main>
        <Header heading={t('h1')} title={t('title')} />
        <div>
          <Link href="/second-page">
            <button type="button">{t('to-second-page')}</button>
          </Link>
        </div>
      </main>
      <Footer />
    </>
  )
}

export default Homepage

const getStaticProps = makeStaticProps(['common', 'footer'])
export { getStaticPaths, getStaticProps }

页面通过 useTranslation(来自 next-i18next/pages,即 react-i18next 的 Hook)按 namespace 取翻译键。静态生成逻辑被封装在 lib/getStatic.js:

import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations'
import i18nextConfig from '../next-i18next.config'

export const getI18nPaths = () =>
  i18nextConfig.i18n.locales.map(lng => ({
    params: { locale: lng },
  }))

export const getStaticPaths = () => ({
  fallback: false,
  paths: getI18nPaths(),
})

export const getI18nProps = async (ctx, ns = ['common']) => {
  const locale = ctx?.params?.locale || i18nextConfig.i18n.defaultLocale
  let props = {
    ...(await serverSideTranslations(locale, ns)),
  }
  return props
}

export const makeStaticProps =
  (ns = []) =>
  async ctx => ({
    props: await getI18nProps(ctx, ns),
  })

关键点:

  • getStaticPaths 返回 fallback: false + 全部语言路径,构建时为 en/de/it 各生成一份 HTML,无需服务端运行时;
  • getI18nProps 把 ctx.params.locale(未传则回退到 defaultLocale)与 namespace 列表交给 serverSideTranslations,返回可直接注入 pageProps 的翻译数据;
  • makeStaticProps(ns) 是一个工厂函数,方便为不同页面声明各自的 namespace 列表。

4.3 serverSideTranslations:服务端翻译数据如何生成

serverSideTranslations 的实现位于 src/pagesRouter/serverSideTranslations.ts。它按以下流程工作:

  1. 校验 initialLocale 必须是字符串,否则抛出明确错误,提示在非 Next.js locale 路由场景(如自定义 404/500、output: 'export')下必须显式传入 locale;
  2. 解析 ./next-i18next.config.js 获取用户配置(可通过环境变量 I18NEXT_DEFAULT_CONFIG_PATH 覆盖配置文件路径);
  3. 用 createConfig 合并默认配置与服务端配置,通过 node 端 createClient 初始化 i18next 实例;
  4. 如果 namespacesRequired 未显式传入,则扫描 public/locales/<locale> 目录下的所有 json 文件自动推断 namespace;
  5. 构建 initialI18nStore(按 locale × namespace 的资源快照),连同 initialLocale、ns、序列化后的 userConfig 一起打包进 _nextI18Next 字段返回——这就是 pageProps 中最终携带的翻译数据;
  6. reloadOnPrerender 仅在非生产环境生效,避免每次预渲染都去源头(后端/文件系统)重复拉取资源。

4.4 合并自定义数据:getI18nProps 的灵活用法

pages/[locale]/second-page.js 展示了如何把翻译 props 与其他业务数据合并:

export { getStaticPaths }
export const getStaticProps = async ctx => {
  // some data fetched from anywhere...
  const someOtherData = 'hello world'
  return {
    props: {
      ...(await getI18nProps(ctx, ['second-page', 'common', 'footer'])),
      someOtherData,
    },
  }
}

这里没有直接使用 makeStaticProps,而是手动调用 getI18nProps(ctx, ns) 后再展开合并自定义字段,适合页面同时需要「从任意数据源获取的数据」+「翻译资源」的场景。


五、客户端语言检测与自动重定向

纯静态站点没有服务端做语言协商,因此示例在根路径(/)、/second-page 以及 /404 上部署了基于 next-language-detector 的重定向逻辑。

5.1 语言检测器配置

lib/languageDetector.js:

import languageDetector from 'next-language-detector'
import i18nextConfig from '../next-i18next.config'

export default languageDetector({
  fallbackLng: i18nextConfig.i18n.defaultLocale,
  supportedLngs: i18nextConfig.i18n.locales,
})

fallbackLng 与 supportedLngs 直接复用 next-i18next 的语言配置,保证两套机制语言集合一致。

5.2 重定向逻辑

lib/redirect.js 实现了三种导出形态:

export const useRedirect = to => {
  const router = useRouter()
  const target = to || router.asPath

  useEffect(() => {
    const detectedLng = languageDetector.detect()
    if (
      target.startsWith('/' + detectedLng) &&
      router.route === '/404'
    ) {
      // prevent endless loop
      router.replace('/' + detectedLng + router.route)
      return
    }
    languageDetector.cache(detectedLng)
    router.replace('/' + detectedLng + target)
    document.documentElement.lang = detectedLng
  })
  return <></>
}

export const Redirect = () => {
  useRedirect()
  return <></>
}

export const getRedirect = to => () => {
  useRedirect(to)
  return <></>
}

核心流程:进入根页面 → languageDetector.detect() 探测语言(依据 cookie、localStorage、navigator 等策略)→ cache(detectedLng) 记忆选择 → router.replace('/' + detectedLng + target) 重定向到带语言前缀的页面,同时把探测结果写入 document.documentElement.lang。代码中对「已在目标语言前缀路径上却进入 404」的情况做了防死循环保护。

5.3 根路径与兜底页面

pages/index.js、pages/second-page.js 与 pages/404.js 内容一致,都只是:

import { Redirect } from '../lib/redirect'
export default Redirect

即让不带语言前缀的访问统一走重定向。如果你希望根路径直接渲染默认语言(en)的首页,README 与源码中的注释也给出了备选方案:导出 ./[locale]/index 的 Homepage 及其 getStaticProps,保持根路径指向默认语言页面。


六、语言切换与本地化链接

6.1 页脚语言切换器

components/Footer.js 读取 router.query.locale 得到当前语言,遍历 i18nextConfig.i18n.locales 渲染除当前语言外的切换按钮:

{i18nextConfig.i18n.locales.map(locale => {
  if (locale === currentLocale) return null
  return <LanguageSwitchLink locale={locale} key={locale} />
})}

components/LanguageSwitchLink.js 在点击时调用 languageDetector.cache(locale) 持久化语言选择,并同步 document.documentElement.lang:

onClick={() => {
  languageDetector.cache(locale)
  document.documentElement.lang = locale
}}

6.2 带 locale 前缀的 Link

components/Link.js 包装了 next/link,自动为 href 拼接当前 locale 前缀:

let href = rest.href || router.asPath
if (href.indexOf('http') === 0) skipLocaleHandling = true
if (locale && !skipLocaleHandling) {
  href = href ? `/${locale}${href}` : router.pathname.replace('[locale]', locale)
}

外链(以 http 开头)会被跳过处理,站内链接则统一变成 /de/second-page 这类形式。

6.3 html lang 语义

pages/_document.js 从 __NEXT_DATA__.query.locale 读取当前语言(缺失时回退 defaultLocale),设置 <Html lang={currentLocale}>,保证每个语言页面拥有正确的语言语义标签。


七、静态 404 页面:每个语言一份

pages/[locale]/404.js](examples/pages-router-ssg/pages/%5Blocale%5D/404.js) 与普通页面完全一致地使用 getStaticPaths + makeStaticProps(['404', 'common', 'footer']),从而为 en/de/it 各生成一个本地化 404 页面,翻译键来自 [public/locales/en/404.json 等资源文件。

由于 Next.js 静态导出不会自动产出 404,示例通过第一节提到的 postbuild 钩子把 out/404/index.html 复制为根级 out/404.html。注意这里存在一个潜在约束:[locale]/404 的 getStaticPaths 并未包含 404 路径(getI18nPaths 只返回 ['en','de','it']),因此实际生成的是 out/404.html 这一份,配合根路径的 Redirect 处理未带语言前缀的 404 访问——这正是 redirect.js 中针对 router.route === '/404' 防死循环分支存在的意义。


八、可选 Locize 工作流:在线翻译管理

README 明确指出 Locize 的使用是可选的("not mandatory")。其思路是:在「部署」应用前,运行一个下载脚本,用 locize-cli 把翻译从 Locize 云端下载到 next-i18next 默认查找的目录(即 ./public/locales)。

示例中的下载脚本定义在 package.json:

npm run downloadLocales

对应命令为:

locize download --project-id=0842ada9-1d1d-4d48-ab27-08f6a132f558 --cdn-type pro --ver=latest --clean=true --path=./public/locales

参数含义:--project-id 指定 Locize 项目;--cdn-type pro 使用 Pro CDN;--ver=latest 拉取最新版本;--clean=true 清理本地多余资源;--path=./public/locales 指定落地目录,与 next-i18next 的默认 localePath 一致。

这套工作流的价值在于:翻译不再需要手工编辑 JSON 文件,可以由产品/运营在 Locize 平台维护,构建前一次性拉取,既享受静态部署的零运维,又保留云端协作的翻译管理能力。


九、本地化资源组织:public/locales 结构

示例的翻译资源严格遵循 next-i18next 的默认目录约定 public/locales/<lng>/<ns>.json(对应源码默认配置 localePath: './public/locales'、localeStructure: '{{lng}}/{{ns}}'、localeExtension: 'json'):

public/locales/
├── de/   → 404.json, common.json, footer.json, second-page.json
├── en/   → 404.json, common.json, footer.json, second-page.json
└── it/   → 404.json, common.json, footer.json, second-page.json

以 public/locales/en/common.json 为例:

{
  "back-to-home": "Back to home",
  "error-with-status": "A {{statusCode}} error occurred on server",
  "error-without-status": "An error occurred on the server",
  "h1": "A simple example",
  "title": "Home | next-i18next",
  "to-second-page": "To second page"
}

德语与意大利语版本(de/common.json、it/common.json)一一对应,并演示了 i18next 插值语法 {{statusCode}}。footer 命名空间(footer.json)则承载了页脚这种「非页面组件」的独立翻译,体现了「组件级命名空间」的组织方式——页面通过 useTranslation(['common', 'footer']) 同时加载多个命名空间,跨命名空间取键时使用 t('common:back-to-home') 这种前缀语法。


十、总结:静态国际化方案的完整链路

回顾整个 pages-router-ssg 示例,一条完整的静态国际化链路清晰可见:

  1. 配置层:next-i18next.config.js 声明语言集合,next.config.js 开启 output: 'export';
  2. 构建层:getStaticPaths(fallback: false)+ makeStaticProps/getI18nProps 为每种语言预渲染 HTML,serverSideTranslations 在构建期生成翻译快照注入 pageProps._nextI18Next;
  3. 运行时层:appWithTranslation 在浏览器端重建 i18next 实例并提供给 useTranslation;
  4. 体验层:next-language-detector 负责首访语言探测与重定向,LanguageSwitchLink 负责切换并持久化,Link 组件统一拼接语言前缀;
  5. 兜底层:本地化 404 页面 + postbuild 复制脚本,保证任何错误路径都有对应的语言版本。

这种「纯静态导出 + 客户端语言检测」的组合,让多语言站点可以部署在任何静态文件服务器上,无需 Node.js 运行时,同时保留了完整的翻译能力——这也是 README 中将其定位为 next-i18next 静态化最佳实践示例的原因。如果你想了解 Pages Router 下非静态(SSR)用法的对比,可以参考仓库中的 pages-router-simple 示例;而 src/pagesRouter 目录下的源码与测试则提供了本文所述机制的完整实现与验证。

登录后查看全文
next-i18next