15 KiB
15 KiB
Internationalization (i18n) Guide
Overview
XPack WebUI supports multiple languages using react-i18next. This guide covers how to implement, maintain, and extend internationalization in the application.
Current Language Support
- English (en): Default language
- Chinese Simplified (zh-CN): Full translation support
Setup and Configuration
i18next Configuration
The i18n system is configured in src/shared/lib/i18n.ts:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
debug: process.env.NODE_ENV === "development",
interpolation: {
escapeValue: false,
},
backend: {
loadPath: "/locales/{{lng}}/{{ns}}.json",
},
detection: {
order: ["localStorage", "navigator", "htmlTag"],
caches: ["localStorage"],
},
});
export default i18n;
Translation Files Structure
public/locales/
├── en/
│ ├── translation.json # Main translations
│ ├── common.json # Common UI elements
│ ├── marketplace.json # Marketplace specific
│ ├── admin.json # Admin console
│ └── errors.json # Error messages
└── zh-CN/
├── translation.json
├── common.json
├── marketplace.json
├── admin.json
└── errors.json
Usage in Components
Basic Translation Hook
import { useTranslation } from '@/shared/lib/useTranslation'
function MyComponent() {
const { t } = useTranslation()
return (
<div>
<h1>{t('Welcome')}</h1>
<p>{t('This is a description')}</p>
</div>
)
}
Namespace-Specific Translations
import { useTranslation } from '@/shared/lib/useTranslation'
function MarketplaceComponent() {
const { t } = useTranslation('marketplace')
return (
<div>
<h1>{t('title')}</h1>
<p>{t('description')}</p>
</div>
)
}
Multiple Namespaces
function AdminComponent() {
const { t: tCommon } = useTranslation('common')
const { t: tAdmin } = useTranslation('admin')
return (
<div>
<button>{tCommon('save')}</button>
<h1>{tAdmin('dashboard.title')}</h1>
</div>
)
}
Translation Patterns
1. Simple Translations
// en/translation.json
{
"welcome": "Welcome",
"goodbye": "Goodbye",
"loading": "Loading..."
}
// zh-CN/translation.json
{
"welcome": "欢迎",
"goodbye": "再见",
"loading": "加载中..."
}
function Component() {
const { t } = useTranslation()
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('loading')}</p>
</div>
)
}
2. Nested Translations
// en/translation.json
{
"user": {
"profile": {
"title": "User Profile",
"edit": "Edit Profile",
"save": "Save Changes"
},
"settings": {
"title": "Settings",
"language": "Language",
"theme": "Theme"
}
}
}
function UserProfile() {
const { t } = useTranslation()
return (
<div>
<h1>{t('user.profile.title')}</h1>
<button>{t('user.profile.edit')}</button>
<button>{t('user.profile.save')}</button>
</div>
)
}
3. Interpolation
// en/translation.json
{
"greeting": "Hello, {{name}}!",
"itemCount": "You have {{count}} items",
"lastLogin": "Last login: {{date, datetime}}"
}
function Component() {
const { t } = useTranslation()
const user = { name: 'John', lastLogin: new Date() }
return (
<div>
<h1>{t('greeting', { name: user.name })}</h1>
<p>{t('itemCount', { count: 5 })}</p>
<p>{t('lastLogin', { date: user.lastLogin })}</p>
</div>
)
}
4. Pluralization
// en/translation.json
{
"item": "{{count}} item",
"item_plural": "{{count}} items",
"notification": {
"one": "You have {{count}} notification",
"other": "You have {{count}} notifications"
}
}
function Component() {
const { t } = useTranslation()
const count = 5
return (
<div>
<p>{t('item', { count })}</p>
<p>{t('notification', { count })}</p>
</div>
)
}
5. Context-Based Translations
// en/translation.json
{
"button": {
"save_male": "Save",
"save_female": "Save",
"delete_male": "Delete",
"delete_female": "Delete"
}
}
function Component() {
const { t } = useTranslation()
const userGender = 'male'
return (
<button>
{t('button.save', { context: userGender })}
</button>
)
}
Language Switching
Language Selector Component
import { useTranslation } from '@/shared/lib/useTranslation'
const languages = [
{ code: 'en', name: 'English', flag: '🇺🇸' },
{ code: 'zh-CN', name: '中文', flag: '🇨🇳' },
]
function LanguageSelector() {
const { i18n, t } = useTranslation()
const changeLanguage = (languageCode: string) => {
i18n.changeLanguage(languageCode)
}
return (
<Select
label={t('common.language')}
selectedKeys={[i18n.language]}
onSelectionChange={(keys) => {
const language = Array.from(keys)[0] as string
changeLanguage(language)
}}
>
{languages.map((lang) => (
<SelectItem key={lang.code} value={lang.code}>
{lang.flag} {lang.name}
</SelectItem>
))}
</Select>
)
}
Programmatic Language Change
import { useTranslation } from "@/shared/lib/useTranslation";
function useLanguage() {
const { i18n } = useTranslation();
const changeLanguage = useCallback(
(language: string) => {
i18n.changeLanguage(language);
// Optionally save to user preferences
localStorage.setItem("preferred-language", language);
},
[i18n]
);
const getCurrentLanguage = () => i18n.language;
return {
currentLanguage: i18n.language,
changeLanguage,
getCurrentLanguage,
};
}
Advanced Features
1. Lazy Loading Translations
// Lazy load namespace
const { t, ready } = useTranslation('admin', { useSuspense: false })
if (!ready) {
return <LoadingSpinner />
}
return <AdminPanel />
2. Translation with HTML
{
"terms": "I agree to the <1>Terms of Service</1> and <3>Privacy Policy</3>"
}
import { Trans } from 'react-i18next'
function TermsComponent() {
return (
<Trans
i18nKey="terms"
components={{
1: <Link href="/terms" />,
3: <Link href="/privacy" />
}}
/>
)
}
3. Date and Number Formatting
// Configure formatters
i18n.init({
// ... other config
interpolation: {
format: (value, format, lng) => {
if (format === "uppercase") return value.toUpperCase();
if (format === "currency") {
return new Intl.NumberFormat(lng, {
style: "currency",
currency: "USD",
}).format(value);
}
if (format === "date") {
return new Intl.DateTimeFormat(lng).format(value);
}
return value;
},
},
});
{
"price": "Price: {{amount, currency}}",
"date": "Created: {{date, date}}"
}
4. Custom Translation Hook
// Custom hook with additional features
export function useAppTranslation(namespace?: string) {
const { t, i18n } = useTranslation(namespace);
const tWithFallback = useCallback(
(key: string, options?: any) => {
const translation = t(key, options);
// Log missing translations in development
if (process.env.NODE_ENV === "development" && translation === key) {
console.warn(`Missing translation for key: ${key}`);
}
return translation;
},
[t]
);
const isRTL = i18n.language === "ar" || i18n.language === "he";
return {
t: tWithFallback,
i18n,
isRTL,
currentLanguage: i18n.language,
};
}
Translation Management
1. Translation File Organization
// en/common.json - Common UI elements
{
"buttons": {
"save": "Save",
"cancel": "Cancel",
"delete": "Delete",
"edit": "Edit",
"close": "Close"
},
"labels": {
"name": "Name",
"email": "Email",
"password": "Password",
"confirmPassword": "Confirm Password"
},
"messages": {
"success": "Operation completed successfully",
"error": "An error occurred",
"loading": "Loading...",
"noData": "No data available"
}
}
// en/marketplace.json - Feature-specific translations
{
"title": "MCP Store",
"subtitle": "Discover and install MCP servers",
"search": {
"placeholder": "Search services...",
"noResults": "No services found",
"filters": {
"category": "Category",
"price": "Price",
"rating": "Rating"
}
},
"service": {
"install": "Install",
"uninstall": "Uninstall",
"details": "View Details",
"rating": "Rating: {{rating}}/5",
"price": "Price: {{price}}"
}
}
2. Translation Validation
// Validation script to check for missing translations
import fs from "fs";
import path from "path";
function validateTranslations() {
const localesDir = path.join(process.cwd(), "public/locales");
const languages = fs.readdirSync(localesDir);
const baseLanguage = "en";
const baseTranslations = loadTranslations(baseLanguage);
languages.forEach((lang) => {
if (lang === baseLanguage) return;
const translations = loadTranslations(lang);
const missingKeys = findMissingKeys(baseTranslations, translations);
if (missingKeys.length > 0) {
console.warn(`Missing translations in ${lang}:`, missingKeys);
}
});
}
function findMissingKeys(base: any, target: any, prefix = ""): string[] {
const missing: string[] = [];
Object.keys(base).forEach((key) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (!(key in target)) {
missing.push(fullKey);
} else if (
typeof base[key] === "object" &&
typeof target[key] === "object"
) {
missing.push(...findMissingKeys(base[key], target[key], fullKey));
}
});
return missing;
}
3. Translation Extraction
// Extract translation keys from components
import { parse } from "@babel/parser";
import traverse from "@babel/traverse";
import fs from "fs";
function extractTranslationKeys(filePath: string): string[] {
const code = fs.readFileSync(filePath, "utf-8");
const ast = parse(code, {
sourceType: "module",
plugins: ["typescript", "jsx"],
});
const keys: string[] = [];
traverse(ast, {
CallExpression(path) {
if (
path.node.callee.type === "Identifier" &&
path.node.callee.name === "t" &&
path.node.arguments[0]?.type === "StringLiteral"
) {
keys.push(path.node.arguments[0].value);
}
},
});
return keys;
}
Best Practices
1. Key Naming Conventions
// Good: Descriptive, hierarchical keys
t("marketplace.service.install.button");
t("user.profile.form.validation.email.required");
t("admin.dashboard.stats.users.total");
// Bad: Generic, flat keys
t("button1");
t("error");
t("text");
2. Consistent Namespace Usage
// Good: Feature-based namespaces
const { t } = useTranslation("marketplace");
const { t: tCommon } = useTranslation("common");
// Bad: Mixed namespace usage
const { t } = useTranslation(); // Default namespace for everything
3. Translation Context
// Good: Provide context for translators
{
"user.status.active": "Active", // User account status
"order.status.active": "Active", // Order processing status
"service.status.active": "Active" // Service running status
}
// Bad: Ambiguous keys
{
"active": "Active" // What kind of active?
}
4. Handling Dynamic Content
// Good: Use interpolation
t("welcome.message", { userName: user.name })// Bad: String concatenation
`Welcome, ${user.name}!`;
5. Error Message Translations
// en/errors.json
{
"validation": {
"required": "This field is required",
"email": "Please enter a valid email address",
"minLength": "Must be at least {{min}} characters",
"maxLength": "Must be no more than {{max}} characters"
},
"api": {
"networkError": "Network error. Please check your connection.",
"serverError": "Server error. Please try again later.",
"unauthorized": "You are not authorized to perform this action."
}
}
Testing Internationalization
1. Component Testing with i18n
import { render, screen } from '@testing-library/react'
import { I18nextProvider } from 'react-i18next'
import i18n from '../test-utils/i18n-for-tests'
import MyComponent from './MyComponent'
function renderWithI18n(component: React.ReactElement) {
return render(
<I18nextProvider i18n={i18n}>
{component}
</I18nextProvider>
)
}
describe('MyComponent', () => {
it('renders translated text', () => {
renderWithI18n(<MyComponent />)
expect(screen.getByText('Welcome')).toBeInTheDocument()
})
it('renders in Chinese', async () => {
await i18n.changeLanguage('zh-CN')
renderWithI18n(<MyComponent />)
expect(screen.getByText('欢迎')).toBeInTheDocument()
})
})
2. Test i18n Configuration
// test-utils/i18n-for-tests.ts
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
i18n.use(initReactI18next).init({
lng: "en",
fallbackLng: "en",
debug: false,
interpolation: {
escapeValue: false,
},
resources: {
en: {
translation: {
Welcome: "Welcome",
Goodbye: "Goodbye",
},
},
"zh-CN": {
translation: {
Welcome: "欢迎",
Goodbye: "再见",
},
},
},
});
export default i18n;
Adding New Languages
1. Create Translation Files
- Create new language directory:
public/locales/[language-code]/ - Copy all JSON files from
en/directory - Translate all values while keeping keys unchanged
2. Update Language Configuration
// Add to language selector
const languages = [
{ code: "en", name: "English", flag: "🇺🇸" },
{ code: "zh-CN", name: "中文", flag: "🇨🇳" },
{ code: "es", name: "Español", flag: "🇪🇸" }, // New language
];
3. Update i18n Configuration
// Add fallback languages if needed
i18n.init({
fallbackLng: {
"zh-CN": ["zh", "en"],
es: ["en"],
default: ["en"],
},
// ... other config
});
This comprehensive i18n guide ensures consistent and maintainable internationalization throughout the XPack WebUI application.