i18n-localization について
アプリ開発者向けの国際化・ローカライズガイドです。テキスト、日付、数値、通貨、複数形、RTL 対応を扱い、React と Node.js の実装例、翻訳ワークフロー、テスト項目を紹介します。
主な機能
- 01国際化とローカライズの概念
- 02テキスト外部化と ICU メッセージ形式
- 03日付・数値・通貨の書式設定
- 04RTL レイアウト対応
- 05React と Node.js の実装例
- 06翻訳ワークフローとローカライズテスト
活用シーン
- 01アプリの多言語対応の基盤を計画
- 02ロケールに応じた日付と通貨の表示
- 03UI への RTL 言語対応の追加
- 04翻訳の網羅性とテキストのはみ出しを確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ travisjneuman/ .claude --skill i18n-localizationインストール後、Claude Code で/i18n-localizationを入力して読み込まれたか確認します。
詳細
国際化とローカライズ
グローバル対応アプリケーションを構築するための包括的なガイドです。
主な概念
用語
i18n (Internationalization):
- Engineering for multiple languages/regions
- Building the infrastructure
- Happens once, during development
L10n (Localization):
- Adapting for specific locale
- Translation, formatting, content
- Happens per locale, ongoing
Locale:
- Language + Region combination
- Format: language-REGION (e.g., en-US, pt-BR)
- Determines formatting rules
ローカライズが必要なもの
| カテゴリ | 例 |
|---|---|
| テキスト | UI ラベル、メッセージ、エラー |
| 数値 | 1,234.56 と 1.234,56 |
| 日付 | MM/DD/YYYY と DD/MM/YYYY |
| 時刻 | 12 時間表記と 24 時間表記 |
| 通貨 | $1,234.56 と €1.234,56 |
| 複数形 | 1 項目、2 項目、5 項目 |
| 方向 | LTR と RTL |
| 画像 | 文化的な適切さ |
| 色 | 文化的な意味 |
| 名前 | 順序、敬称 |
テキストとメッセージ
すべての文字列を外部化する
// DON'T: Hardcoded strings
const message = "Welcome back, " + username;
// DO: Externalized, translatable
const message = t('welcome_back', { name: username });
// Translation file (en.json)
{
"welcome_back": "Welcome back, {{name}}"
}
// Translation file (es.json)
{
"welcome_back": "Bienvenido de nuevo, {{name}}"
}
メッセージ形式
// ICU Message Format (recommended)
// Handles plurals, select, dates, numbers
// Simple
"greeting": "Hello, {name}!"
// Plural
"items_count": "{count, plural, =0 {No items} one {# item} other {# items}}"
// Select (gender, etc.)
"notification": "{gender, select, male {He} female {She} other {They}} liked your post"
// Nested
"cart": "{itemCount, plural,
=0 {Your cart is empty}
one {You have # item in your cart}
other {You have # items in your cart}
}"
複数形化
Languages have different plural rules:
English: 1 (one), 2+ (other)
French: 0-1 (one), 2+ (other)
Russian: Complex rules for 1, 2-4, 5-20, 21, etc.
Arabic: 6 plural forms!
Chinese: No plural forms
Always use library pluralization, never DIY:
- react-intl / formatjs
- i18next
- Intl.PluralRules API
日付と時刻
JavaScript Intl API
// Date formatting
const date = new Date("2024-03-15");
new Intl.DateTimeFormat("en-US").format(date);
// "3/15/2024"
new Intl.DateTimeFormat("de-DE").format(date);
// "15.3.2024"
new Intl.DateTimeFormat("ja-JP").format(date);
// "2024/3/15"
// With options
new Intl.DateTimeFormat("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
}).format(date);
// "Friday, March 15, 2024"
タイムゾーン
// Always store in UTC
const utcDate = new Date().toISOString();
// "2024-03-15T14:30:00.000Z"
// Display in user's timezone
new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
dateStyle: "full",
timeStyle: "long",
}).format(new Date(utcDate));
// "Friday, March 15, 2024 at 10:30:00 AM EDT"
// Get user's timezone
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
相対時間
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
rtf.format(-1, "day"); // "yesterday"
rtf.format(1, "day"); // "tomorrow"
rtf.format(-3, "hour"); // "3 hours ago"
rtf.format(2, "week"); // "in 2 weeks"
// For automatic unit selection, use a library like date-fns
import { formatDistanceToNow } from "date-fns";
formatDistanceToNow(date, { addSuffix: true });
// "3 days ago"
数値と通貨
数値の書式設定
const number = 1234567.89;
new Intl.NumberFormat("en-US").format(number);
// "1,234,567.89"
new Intl.NumberFormat("de-DE").format(number);
// "1.234.567,89"
new Intl.NumberFormat("fr-FR").format(number);
// "1 234 567,89"
// Percentages
new Intl.NumberFormat("en-US", {
style: "percent",
minimumFractionDigits: 1,
}).format(0.256);
// "25.6%"
通貨の書式設定
const amount = 1234.56;
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(amount);
// "$1,234.56"
new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
}).format(amount);
// "1.234,56 €"
new Intl.NumberFormat("ja-JP", {
style: "currency",
currency: "JPY",
}).format(amount);
// "¥1,235" (no decimal for JPY)
通貨のベストプラクティス
// Store amount + currency code
interface Money {
amount: number; // In smallest unit (cents)
currency: string; // ISO 4217 code (USD, EUR, etc.)
}
// Format for display
function formatMoney(money: Money, locale: string): string {
return new Intl.NumberFormat(locale, {
style: "currency",
currency: money.currency,
}).format(money.amount / 100); // Convert cents to units
}
// Handle exchange rates on backend
// Never convert currencies client-side
RTL(右から左)への対応
RTL 言語
RTL Languages:
- Arabic (ar)
- Hebrew (he)
- Persian/Farsi (fa)
- Urdu (ur)
Layout considerations:
┌─────────────────────────────┐ ┌─────────────────────────────┐
│ Logo Menu Settings │ │ Settings Menu Logo │
│ ← Back │ │ Back → │
│ [Icon] Label │ │ Label [Icon] │
│ Next → │ │ ← Next │
└─────────────────────────────┘ └─────────────────────────────┘
LTR Layout RTL Layout
RTL 用 CSS
/* Use logical properties */
/* DON'T: Physical properties */
.element {
margin-left: 10px;
padding-right: 20px;
text-align: left;
float: left;
}
/* DO: Logical properties */
.element {
margin-inline-start: 10px;
padding-inline-end: 20px;
text-align: start;
float: inline-start;
}
/* Set direction based on locale */
html[dir="rtl"] {
direction: rtl;
}
/* Or use :dir() pseudo-class */
.icon:dir(rtl) {
transform: scaleX(-1); /* Mirror icons */
}
/* Flexbox auto-reverses in RTL */
.container {
display: flex;
/* No need to change for RTL */
}
HTML の方向
<html lang="ar" dir="rtl">
<div dir="auto">
مرحبا بالعالم
</div>
<p>The word <bdi>مرحبا</bdi> means "hello".</p>
</html>
実装(React)
react-intl のセットアップ
// src/i18n/index.ts
import { createIntl, createIntlCache } from '@formatjs/intl';
const cache = createIntlCache();
const messages = {
en: () => import('./locales/en.json'),
es: () => import('./locales/es.json'),
fr: () => import('./locales/fr.json'),
};
export async function loadMessages(locale: string) {
const loader = messages[locale] || messages.en;
return (await loader()).default;
}
// App.tsx
import { IntlProvider } from 'react-intl';
function App() {
const [locale, setLocale] = useState('en');
const [messages, setMessages] = useState({});
useEffect(() => {
loadMessages(locale).then(setMessages);
}, [locale]);
return (
<IntlProvider locale={locale} messages={messages}>
<MainApp />
</IntlProvider>
);
}
翻訳の使用
import { FormattedMessage, useIntl } from "react-intl";
function ProductCard({ product }) {
const intl = useIntl();
return (
<div>
{/* Component-based */}
<h2>
<FormattedMessage id="product.title" values={{ name: product.name }} />
</h2>
{/* Hook-based (for attributes, etc.) */}
<img
src={product.image}
alt={intl.formatMessage({ id: "product.image_alt" })}
/>
{/* Numbers */}
<p>
<FormattedNumber
value={product.price}
style="currency"
currency="USD"
/>
</p>
{/* Dates */}
<p>
<FormattedDate value={product.createdAt} dateStyle="medium" />
</p>
{/* Plurals */}
<p>
<FormattedMessage
id="product.reviews"
values={{ count: product.reviewCount }}
/>
</p>
</div>
);
}
翻訳ファイル
// locales/en.json
{
"product.title": "{name}",
"product.image_alt": "Photo of {name}",
"product.reviews": "{count, plural, =0 {No reviews} one {# review} other {# reviews}}",
"cart.empty": "Your cart is empty",
"cart.checkout": "Proceed to checkout"
}
// locales/es.json
{
"product.title": "{name}",
"product.image_alt": "Foto de {name}",
"product.reviews": "{count, plural, =0 {Sin reseñas} one {# reseña} other {# reseñas}}",
"cart.empty": "Tu carrito está vacío",
"cart.checkout": "Proceder al pago"
}
実装(Node.js)
i18next のセットアップ
import i18next from "i18next";
import Backend from "i18next-fs-backend";
await i18next.use(Backend).init({
lng: "en",
fallbackLng: "en",
supportedLngs: ["en", "es", "fr", "de"],
backend: {
loadPath: "./locales/{{lng}}/{{ns}}.json",
},
interpolation: {
escapeValue: false,
},
});
// Usage
const t = i18next.t;
t("welcome", { name: "John" });
// "Welcome, John!"
// Change language
await i18next.changeLanguage("es");
Express ミドルウェア
import { Request, Response, NextFunction } from "express";
function detectLocale(req: Request, res: Response, next: NextFunction) {
// Priority: Query param > Cookie > Accept-Language header > Default
const locale =
req.query.locale ||
req.cookies.locale ||
req.acceptsLanguages(["en", "es", "fr"]) ||
"en";
req.locale = locale;
req.t = i18next.getFixedT(locale);
next();
}
app.use(detectLocale);
app.get("/api/greeting", (req, res) => {
res.json({
message: req.t("greeting", { name: req.user.name }),
});
});
翻訳ワークフロー
ファイル構成
locales/
├── en/
│ ├── common.json # Shared strings
│ ├── auth.json # Auth-related
│ ├── products.json # Product-related
│ └── errors.json # Error messages
├── es/
│ └── ...
├── fr/
│ └── ...
└── _source/
└── en.json # Source of truth
キーの命名規則
{
// Feature.element.description
"auth.login.button": "Sign In",
"auth.login.error.invalid_credentials": "Invalid email or password",
// Or flat with prefixes
"btn_login": "Sign In",
"err_invalid_credentials": "Invalid email or password"
// Consistent, descriptive, unique
}
翻訳管理
TOOLS:
- Lokalise, Crowdin, Phrase (SaaS platforms)
- Weblate (open source)
- POEditor, Transifex
WORKFLOW:
1. Extract strings from code
2. Upload to translation platform
3. Translators work in context
4. Review translations
5. Download and integrate
6. Test in app
7. Repeat for changes
AUTOMATION:
- CI/CD integration
- Automatic string extraction
- Translation memory
- Machine translation + human review
テスト
疑似ローカライズ
// Transforms: "Hello" → "[Ħëľľö!!!]"
// Helps identify:
// - Hardcoded strings
// - Text truncation issues
// - Character encoding problems
// - Layout issues with longer text
function pseudoLocalize(text: string): string {
const charMap: Record<string, string> = {
a: "ä",
b: "β",
c: "ç",
d: "δ",
e: "ë",
// ... etc
};
const transformed = text
.split("")
.map((c) => charMap[c.toLowerCase()] || c)
.join("");
// Add padding (most translations are 30% longer)
const padding = "!".repeat(Math.ceil(text.length * 0.3));
return `[${transformed}${padding}]`;
}
ロケールテストのチェックリスト
FOR EACH LOCALE:
□ All strings translated
□ No hardcoded text visible
□ Dates format correctly
□ Numbers format correctly
□ Currency displays properly
□ Plurals work for all cases
□ UI accommodates text length
□ RTL layout correct (if applicable)
□ Images are appropriate
□ No encoding issues
□ Forms validate appropriately
ベストプラクティス
実施すること:
- ユーザーに表示される文字列をすべて外部化する
- 複雑な文字列には ICU メッセージ形式を使用する
- 再読み込みなしでロケールを切り替えられるようにする
- 疑似ローカライズでテストする
- 日付は UTC で保存し、現地時間で表示する
- 可能な限りネイティブの Intl API を使用する
- テキストの拡張(30〜50%長くなる)を想定する
- 最初から RTL に対応する
実施しないこと:
- ユーザーに表示されるテキストをハードコードする
- メッセージ用の文字列を連結する
- 日付や数値の書式を決めつける
- 複数形を手動で処理する
- 文化的背景を忘れる
- コード内で翻訳する(翻訳ファイルを使用する)
- 双方向テキストの問題を無視する
- 実際の言語でのテストを省略する
チェックリスト
初期設定
- i18n ライブラリを選択する
- 翻訳ファイルの構成を設定する
- ロケール検出を設定する
- ロケール切り替え UI を追加する
- RTL 対応を設定する
機能ごと
- すべての文字列を翻訳ファイルに抽出する
- 変数にはメッセージ形式を使用する
- 複数形を正しく処理する
- 日付、数値、通貨の書式を設定する
- 疑似ローカライズでテストする
- 文脈の中でテキストを確認する
リリース
- プロによる翻訳を完了する
- すべてのロケールをテストする
- RTL レイアウトを検証する
- 多言語向け SEO(hreflang)を設定する
- ロケール固有のコンテンツを確認する
コメント
Markdown 対応