Frontend-i18n-Architektur in der Praxis: next-intl, react-i18next und mehrsprachiges SEO

前端工程

i18n ist mehr als Text übersetzen

i18n umfasst Übersetzung, Typografie, Datums-/Zahlenformatierung, Währung, Pluralformen, RTL, SEO – wesentlich komplexer als einfach „ein Sprachpaket wechseln."

Dimension Beispiel
Übersetzung "Hello" → "你好" → "こんにちは"
Datumsformat 2026/06/02 vs 02/06/2026 vs 06.02.2026
Zahlenformat 1,234.56 vs 1.234,56 vs 1 234,56
Währung ¥1,234 vs $1,234 vs €1.234
Pluralformen 1 item vs 2 items (Chinesisch hat keine Pluralflexion)
Textrichtung LTR (Chinesisch/Englisch) vs RTL (Arabisch)
URL-Strategie /en/about vs /about?lang=en

1. Organisation der Übersetzungsdateien

Namespace-basierte Aufteilung

messages/
├── zh-CN/
│   ├── common.json       # General: buttons, navigation, errors
│   ├── home.json         # Homepage
│   ├── auth.json         # Login/Register
│   ├── dashboard.json    # Dashboard
│   └── errors.json       # Error messages
├── en/
│   ├── common.json
│   ├── home.json
│   └── ...
└── ja/
    ├── common.json
    └── ...

JSON-Struktur

{
  "common": {
    "button": {
      "submit": "Submit",
      "cancel": "Cancel",
      "confirm": "Confirm"
    },
    "nav": {
      "home": "Home",
      "about": "About",
      "contact": "Contact Us"
    }
  },
  "home": {
    "title": "Free Online Toolkit",
    "subtitle": "200+ tools, browser-side processing, private and secure",
    "cta": "Get Started"
  }
}

Verschachtelte Schlüssel abflachen

// Nested style
{ "home": { "hero": { "title": "Toolkit" } } }

// Equivalent flat style
{ "home.hero.title": "Toolkit" }

2. next-intl in der Praxis

Konfiguration

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

export const routing = defineRouting({
  locales: ['zh-CN', 'zh-TW', 'en', 'ja', 'es-419', 'pt-BR', 'de', 'ru', 'fr'],
  defaultLocale: 'zh-CN',
  localePrefix: 'always', // /zh-CN/about
});

Serverseitige Verwendung

// 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>
  );
}

Clientseitige Verwendung

'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>
  );
}

3. ICU-Nachrichtenformat

Variableninterpolation

{
  "greeting": "Hello, {name}!",
  "fileCount": "{count} files uploaded"
}
t('greeting', { name: 'John' })       // Hello, John!
t('fileCount', { count: 5 })          // 5 files uploaded

Pluralbehandlung

{
  "items": "{count, plural, =0 {No items} =1 {1 item} other {# items}}"
}
count Englisch
0 No items
1 1 item
5 5 items

Select-Format (Geschlecht usw.)

{
  "invitation": "{gender, select, male {Invite him} female {Invite her} other {Invite them}}"
}

Rich Text

{
  "terms": "Click <link>this link</link> to view terms"
}
<p>{t.rich('terms', {
  link: (children) => <a href="/terms">{children}</a>
})}</p>

4. Datums- und Zahlenformatierung

Datumsformat

import { useFormatter } from 'next-intl';

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

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

      {/* English: June 2, 2026 */}
      {/* Japanese: 2026年6月2日 */}

      {/* Custom format */}
      <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>
  );
}

Zahlen- und Währungsformat

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

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

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

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

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

5. RTL-Unterstützung

Erkennung und Einrichtung

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 logische Eigenschaften

/* Use logical properties for automatic RTL adaptation */
.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 */
}

6. Mehrsprachiges SEO

hreflang-Tags

<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 Metadaten-Generierung

// 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',
      },
    },
  };
}

Mehrsprachige Sitemap

// src/app/sitemap.ts
export default function sitemap() {
  const locales = ['zh-CN', 'zh-TW', 'en', 'ja', 'es-419', 'pt-BR', 'de', 'ru', 'fr'];
  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,
    }))
  );
}

7. Vergleich der URL-Strategien

Strategie Beispiel SEO Technische Komplexität
Sub-Pfad /zh-CN/about Gut Niedrig
Sub-Domain cn.example.com/about Gut Mittel
Query-Parameter /about?lang=zh-CN Schlecht Niedrig
Separate Domain example.cn/about Gut Hoch

Empfehlung: Sub-Pfad-Strategie – SEO-freundlich und einfach umzusetzen.


8. Qualitätssicherung der Übersetzung

i18n-Validierungsskript

// 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 keys:`, missing);
  if (extra.length) console.log(`[${locale}] Extra keys:`, extra);
}

CI-Integration

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

Übersetzungs-Workflow

  1. Entwickler ändern nur die zh-CN-Dateien
  2. CI validiert die Vollständigkeit der Schlüssel für andere Sprachen
  3. Neue Schlüssel werden automatisch als übersetzungspending markiert
  4. Die Übersetzungsplattform (Crowdin/Transifex) synchronisiert
  5. Automatischer PR nach Abschluss der Übersetzung

Probiere diese browser-lokalen Tools aus — keine Registrierung erforderlich →

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