Arquitetura i18n Frontend na Prática: next-intl, react-i18next e SEO Multilíngue
前端工程
i18n é mais do que traduzir texto
i18n envolve tradução, tipografia, formatação de datas/números, moeda, plurais, RTL, SEO—muito mais complexo do que simplesmente "trocar um pacote de idioma."
| Dimensão | Exemplo |
|---|---|
| Tradução | "Hello" → "你好" → "こんにちは" |
| Formato de data | 2026/06/02 vs 02/06/2026 vs 06.02.2026 |
| Formato numérico | 1,234.56 vs 1.234,56 vs 1 234,56 |
| Moeda | ¥1,234 vs $1,234 vs €1.234 |
| Plurais | 1 item vs 2 items (o chinês não tem inflexão plural) |
| Direção do texto | LTR (chinês/inglês) vs RTL (árabe) |
| Estratégia de URL | /en/about vs /about?lang=en |
1. Organização de arquivos de tradução
Divisão baseada em namespaces
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
└── ...
Estrutura JSON
{
"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"
}
}
Achatar chaves aninhadas
// Nested style
{ "home": { "hero": { "title": "Toolkit" } } }
// Equivalent flat style
{ "home.hero.title": "Toolkit" }
2. next-intl na prática
Configuração
// 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
});
Uso no lado do servidor
// 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>
);
}
Uso no lado do cliente
'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. Formato de mensagens ICU
Interpolação de variáveis
{
"greeting": "Hello, {name}!",
"fileCount": "{count} files uploaded"
}
t('greeting', { name: 'John' }) // Hello, John!
t('fileCount', { count: 5 }) // 5 files uploaded
Tratamento de plurais
{
"items": "{count, plural, =0 {No items} =1 {1 item} other {# items}}"
}
| count | Inglês |
|---|---|
| 0 | No items |
| 1 | 1 item |
| 5 | 5 items |
Formato select (gênero, etc.)
{
"invitation": "{gender, select, male {Invite him} female {Invite her} other {Invite them}}"
}
Texto enriquecido
{
"terms": "Click <link>this link</link> to view terms"
}
<p>{t.rich('terms', {
link: (children) => <a href="/terms">{children}</a>
})}</p>
4. Formatação de datas e números
Formato de data
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>
);
}
Formato de números e moeda
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. Suporte RTL
Detecção e configuração
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>
);
}
Propriedades lógicas CSS
/* 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. SEO multilíngue
Tags 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" />
Geração de metadados no Next.js
// 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 multilíngue
// 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. Comparação de estratégias de URL
| Estratégia | Exemplo | SEO | Complexidade técnica |
|---|---|---|---|
| Sub-caminho | /zh-CN/about |
Bom | Baixa |
| Sub-domínio | cn.example.com/about |
Bom | Média |
| Parâmetro de consulta | /about?lang=zh-CN |
Ruim | Baixa |
| Domínio separado | example.cn/about |
Bom | Alta |
Recomendação: Estratégia de sub-caminho—amigável para SEO e fácil de implementar.
8. Garantia de qualidade de tradução
Script de validação 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 keys:`, missing);
if (extra.length) console.log(`[${locale}] Extra keys:`, extra);
}
Integração CI
- name: i18n check
run: node scripts/i18n-check.js
Fluxo de trabalho de tradução
- Desenvolvedores modificam apenas os arquivos
zh-CN - CI valida a completude de chaves para outros idiomas
- Novas chaves são marcadas automaticamente como pendentes de tradução
- A plataforma de tradução (Crowdin/Transifex) sincroniza
- PR automático após a conclusão da tradução
Experimente estas ferramentas executadas localmente no navegador — nenhum cadastro necessário →
#i18n#国际化#next-intl#react-i18next#SEO#多语言