前端国际化 i18n 架构实战:next-intl、react-i18next 与多语言 SEO 全覆盖

前端开发

国际化不只是翻译文字

i18n 涉及翻译、排版、日期/数字格式、货币、复数、RTL、SEO——远比"换个语言包"复杂。

维度 示例
翻译 "Hello" → "你好" → "こんにちは"
日期格式 2026/06/02 vs 02/06/2026 vs 06.02.2026
数字格式 1,234.56 vs 1.234,56 vs 1 234,56
货币 ¥1,234 vs $1,234 vs €1.234
复数 1 item vs 2 items(中文无复数变化)
排版方向 LTR(中文/英文)vs RTL(阿拉伯语)
URL 策略 /en/about vs /about?lang=en

一、翻译文件组织

按命名空间拆分

messages/
├── zh-CN/
│   ├── common.json       # 通用:按钮、导航、错误
│   ├── home.json         # 首页
│   ├── auth.json         # 登录/注册
│   ├── dashboard.json    # 仪表盘
│   └── errors.json       # 错误消息
├── en/
│   ├── common.json
│   ├── home.json
│   └── ...
└── ja/
    ├── common.json
    └── ...

JSON 结构

{
  "common": {
    "button": {
      "submit": "提交",
      "cancel": "取消",
      "confirm": "确认"
    },
    "nav": {
      "home": "首页",
      "about": "关于",
      "contact": "联系我们"
    }
  },
  "home": {
    "title": "免费在线工具箱",
    "subtitle": "200+ 工具,浏览器本地处理,隐私安全",
    "cta": "开始使用"
  }
}

嵌套键的扁平化

// 嵌套写法
{ "home": { "hero": { "title": "工具箱" } } }

// 等价扁平写法
{ "home.hero.title": "工具箱" }

二、next-intl 实战

配置

// src/i18n/routing.ts
import { defineRouting } from 'next-intl/routing';

export const routing = defineRouting({
  locales: ['zh-CN', 'zh-TW', 'en', 'ja'],
  defaultLocale: 'zh-CN',
  localePrefix: 'always', // /zh-CN/about
});

服务端使用

// src/app/[locale]/page.tsx
import { useTranslations } from 'next-intl';

export default function HomePage() {
  const t = useTranslations('home');
  return (
    <div>
      <h1>{t('title')}</h1>
      <p>{t('subtitle')}</p>
    </div>
  );
}

客户端使用

'use client';
import { useTranslations } from 'next-intl';

function LanguageSwitcher() {
  const router = useRouter();
  const pathname = usePathname();
  const locale = useLocale();

  function switchLocale(newLocale: string) {
    router.replace(pathname.replace(`/${locale}`, `/${newLocale}`));
  }

  return (
    <select value={locale} onChange={(e) => switchLocale(e.target.value)}>
      <option value="zh-CN">简体中文</option>
      <option value="zh-TW">繁體中文</option>
      <option value="en">English</option>
      <option value="ja">日本語</option>
    </select>
  );
}

三、ICU 消息格式

变量插值

{
  "greeting": "你好,{name}!",
  "fileCount": "已上传 {count} 个文件"
}
t('greeting', { name: '张三' })       // 你好,张三!
t('fileCount', { count: 5 })          // 已上传 5 个文件

复数处理

{
  "items": "{count, plural, =0 {没有项目} =1 {1 个项目} other {# 个项目}}"
}
count 中文 英文
0 没有项目 0 items
1 1 个项目 1 item
5 5 个项目 5 items

选择格式(性别等)

{
  "invitation": "{gender, select, male {邀请他} female {邀请她} other {邀请他们}}"
}

富文本

{
  "terms": "点击 <link>此链接</link> 查看条款"
}
<p>{t.rich('terms', {
  link: (children) => <a href="/terms">{children}</a>
})}</p>

四、日期与数字格式化

日期格式

import { useFormatter } from 'next-intl';

function DateFormatter({ date }: { date: Date }) {
  const format = useFormatter();

  return (
    <div>
      {/* 中文:2026年6月2日 */}
      <p>{format.dateTime(date, { dateStyle: 'long' })}</p>

      {/* 英文:June 2, 2026 */}
      {/* 日文:2026年6月2日 */}

      {/* 自定义格式 */}
      <p>{format.dateTime(date, {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })}</p>
      {/* zh-CN: 2026/06/02 */}
      {/* en: 06/02/2026 */}
      {/* ja: 2026/06/02 */}
    </div>
  );
}

数字与货币格式

function NumberFormatter() {
  const format = useFormatter();

  return (
    <div>
      {/* 数字 */}
      {format.number(1234.56)}          {/* zh-CN: 1,234.56 | de: 1.234,56 */}

      {/* 货币 */}
      {format.number(1234, { style: 'currency', currency: 'CNY' })}
      {/* zh-CN: ¥1,234.00 | en-US: CN¥1,234.00 */}

      {/* 百分比 */}
      {format.number(0.856, { style: 'percent' })}
      {/* zh-CN: 86% | en: 86% */}

      {/* 单位 */}
      {format.number(1024, { style: 'unit', unit: 'megabyte' })}
      {/* zh-CN: 1,024 MB | en: 1,024 MB */}
    </div>
  );
}

五、RTL 支持

检测与设置

import { useLocale } from 'next-intl';

const RTL_LOCALES = ['ar', 'he', 'fa', 'ur'];

function AppLayout({ children }) {
  const locale = useLocale();
  const dir = RTL_LOCALES.includes(locale) ? 'rtl' : 'ltr';

  return (
    <html dir={dir} lang={locale}>
      <body>{children}</body>
    </html>
  );
}

CSS 逻辑属性

/* 使用逻辑属性,自动适配 RTL */
.card {
  margin-inline-start: 1rem;    /* LTR: margin-left | RTL: margin-right */
  padding-inline-end: 0.5rem;   /* LTR: padding-right | RTL: padding-left */
  border-inline-start: 2px solid blue;
  text-align: start;            /* LTR: left | RTL: right */
}

六、多语言 SEO

hreflang 标签

<link rel="alternate" hreflang="zh-CN" href="https://example.com/zh-CN/about" />
<link rel="alternate" hreflang="zh-TW" href="https://example.com/zh-TW/about" />
<link rel="alternate" hreflang="en" href="https://example.com/en/about" />
<link rel="alternate" hreflang="ja" href="https://example.com/ja/about" />
<link rel="alternate" hreflang="x-default" href="https://example.com/en/about" />

Next.js metadata 生成

// src/app/[locale]/about/layout.tsx
export async function generateMetadata({ params: { locale } }) {
  const t = await getTranslations({ locale, namespace: 'about' });

  return {
    title: t('metaTitle'),
    description: t('metaDescription'),
    alternates: {
      canonical: `https://example.com/${locale}/about`,
      languages: {
        'zh-CN': 'https://example.com/zh-CN/about',
        'zh-TW': 'https://example.com/zh-TW/about',
        'en': 'https://example.com/en/about',
        'ja': 'https://example.com/ja/about',
        'x-default': 'https://example.com/en/about',
      },
    },
  };
}

Sitemap 多语言

// src/app/sitemap.ts
export default function sitemap() {
  const locales = ['zh-CN', 'zh-TW', 'en', 'ja'];
  const pages = ['/', '/about', '/tools', '/blog'];

  return locales.flatMap(locale =>
    pages.map(page => ({
      url: `https://example.com/${locale}${page}`,
      lastModified: new Date(),
      changeFrequency: 'weekly',
      priority: page === '/' ? 1 : 0.8,
    }))
  );
}

七、URL 策略对比

策略 示例 SEO 技术复杂度
子路径 /zh-CN/about
子域名 cn.example.com/about
参数 /about?lang=zh-CN
独立域名 example.cn/about

推荐:子路径策略,SEO 友好且实现简单。


八、翻译质量保障

i18n 校验脚本

// scripts/i18n-check.js
const fs = require('fs');
const path = require('path');

const locales = ['zh-CN', 'en', 'ja'];
const baseLocale = 'zh-CN';

function flattenKeys(obj, prefix = '') {
  return Object.entries(obj).flatMap(([key, value]) =>
    typeof value === 'object'
      ? flattenKeys(value, prefix ? `${prefix}.${key}` : key)
      : [prefix ? `${prefix}.${key}` : key]
  );
}

const baseKeys = flattenKeys(JSON.parse(fs.readFileSync(`messages/${baseLocale}/common.json`, 'utf-8')));

for (const locale of locales.filter(l => l !== baseLocale)) {
  const localeKeys = flattenKeys(JSON.parse(fs.readFileSync(`messages/${locale}/common.json`, 'utf-8')));
  const missing = baseKeys.filter(k => !localeKeys.includes(k));
  const extra = localeKeys.filter(k => !baseKeys.includes(k));

  if (missing.length) console.log(`[${locale}] 缺少键:`, missing);
  if (extra.length) console.log(`[${locale}] 多余键:`, extra);
}

CI 集成

- name: i18n check
  run: node scripts/i18n-check.js

翻译工作流

  1. 开发者只修改 zh-CN 文件
  2. CI 校验其他语言键的完整性
  3. 新键自动标记为待翻译
  4. 翻译平台(Crowdin/Transifex)同步
  5. 翻译完成后自动 PR 回合

本站提供浏览器本地工具,免注册即可试用 →

#i18n#国际化#next-intl#react-i18next#SEO#多语言