延迟加载
按需加载命名空间
// 初始化时只加载必要的命名空间
i18next.init({
ns: ['translation', 'common'],
defaultNS: 'translation'
});
// 需要时加载其他命名空间
i18next.loadNamespaces(['admin', 'settings'], (err, t) => {
if (!err) {
console.log('命名空间加载完成');
}
});
按需加载语言
// 初始化时只加载默认语言
i18next.init({
lng: 'en',
preload: ['en'] // 只预加载英语
});
// 用户切换语言时加载
i18next.loadLanguages(['zh', 'fr'], () => {
console.log('语言资源加载完成');
});
React 中的 Suspense 模式
import { useTranslation } from 'react-i18next';
import { Suspense } from 'react';
function LazyComponent() {
const { t } = useTranslation('lazyNamespace');
return <p>{t('content')}</p>;
}
function App() {
return (
<Suspense fallback={<div>Loading translations...</div>}>
<LazyComponent />
</Suspense>
);
}
缓存策略
本地存储缓存
import LocalStorageBackend from 'i18next-localstorage-backend';
import HttpBackend from 'i18next-http-backend';
i18next
.use(HttpBackend)
.use(LocalStorageBackend)
.init({
backend: {
backends: [
LocalStorageBackend,
HttpBackend
],
backendOptions: [
{
expirationTime: 7 * 24 * 60 * 60 * 1000, // 7天过期
defaultVersion: 'v1.0.0',
store: window.localStorage
},
{
loadPath: '/locales/{{lng}}/{{ns}}.json'
}
]
}
});
内存缓存
const translationCache = new Map();
function getCachedTranslation(key, options) {
const cacheKey = `${key}_${JSON.stringify(options)}`;
if (translationCache.has(cacheKey)) {
return translationCache.get(cacheKey);
}
const translation = i18next.t(key, options);
translationCache.set(cacheKey, translation);
return translation;
}
缓存失效策略
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json?v={{version}}',
queryStringParams: {
version: process.env.TRANSLATION_VERSION || '1.0.0'
}
}
资源优化
压缩翻译资源
// 使用 gzip 压缩
// 服务器配置示例 (Express)
const express = require('express');
const compression = require('compression');
const app = express();
app.use(compression());
app.use('/locales', express.static('locales'));
按功能拆分翻译文件
// 文件结构
// locales/
// ├── en/
// │ ├── common.json
// │ ├── admin.json
// │ ├── user.json
// │ └── settings.json
// └── zh/
// ├── common.json
// ├── admin.json
// ├── user.json
// └── settings.json
// 配置
i18next.init({
ns: ['common', 'admin', 'user', 'settings'],
defaultNS: 'common'
});
移除未使用的翻译
// 构建时分析代码中使用的翻译键
const usedKeys = analyzeTranslationKeysInCode();
const allTranslations = loadAllTranslations();
const optimizedTranslations = filterTranslations(allTranslations, usedKeys);
saveOptimizedTranslations(optimizedTranslations);
请求优化
批量加载
// 一次性加载多个命名空间
Promise.all([
i18next.loadNamespaces(['admin', 'settings', 'reports']),
i18next.loadLanguages(['en', 'zh'])
]).then(() => {
console.log('所有翻译资源加载完成');
});
预加载关键资源
i18next.init({
preload: ['en', 'zh'], // 预加载的语言
ns: ['translation', 'common'], // 预加载的命名空间
partialBundledLanguages: true // 允许部分加载
});
使用 CDN
backend: {
loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json',
crossDomain: true
}
运行时优化
避免频繁翻译
// 不好的做法
function renderList(items) {
return items.map(item => (
<div key={item.id}>
<h3>{t('item.title', { name: item.name })}</h3>
<p>{t('item.description', { desc: item.description })}</p>
</div>
));
}
// 好的做法 - 缓存翻译
function renderList(items) {
const titleTemplate = t('item.title');
const descTemplate = t('item.description');
return items.map(item => (
<div key={item.id}>
<h3>{titleTemplate.replace('{{name}}', item.name)}</h3>
<p>{descTemplate.replace('{{desc}}', item.description)}</p>
</div>
));
}
使用 React.memo 优化
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
const TranslatedComponent = memo(({ text }) => {
const { t } = useTranslation();
return <span>{t(text)}</span>;
});
虚拟滚动优化长列表
import { FixedSizeList } from 'react-window';
function TranslatedList({ items }) {
const { t } = useTranslation();
const Row = ({ index, style }) => (
<div style={style}>
{t(items[index].key)}
</div>
);
return (
<FixedSizeList
height={400}
itemCount={items.length}
itemSize={35}
>
{Row}
</FixedSizeList>
);
}
监控和分析
性能监控
i18next.on('loaded', (loaded) => {
console.log('翻译资源加载完成:', loaded);
// 发送性能指标到监控系统
trackPerformance('i18n_loaded', {
namespaces: Object.keys(loaded),
timestamp: Date.now()
});
});
错误监控
i18next.on('failedLoading', (lng, ns, msg) => {
console.error('翻译资源加载失败:', { lng, ns, msg });
// 发送错误到监控系统
trackError('i18n_load_failed', { lng, ns, msg });
});
最佳实践总结
- 延迟加载: 只加载当前需要的翻译资源
- 缓存策略: 使用本地存储和内存缓存减少网络请求
- 资源优化: 压缩、拆分和清理翻译文件
- 请求优化: 批量加载、预加载和使用 CDN
- 运行时优化: 避免频繁翻译、使用 memo 和虚拟滚动
- 监控: 监控加载性能和错误率
- 版本控制: 使用版本号管理翻译资源更新