基本初始化
i18next 的初始化非常简单,使用 i18next.init() 方法进行配置:
javascriptimport i18next from 'i18next'; i18next.init({ lng: 'en', // 默认语言 debug: true, // 开发模式下开启调试 resources: { en: { translation: { "key": "Hello World" } }, zh: { translation: { "key": "你好世界" } } } }, (err, t) => { if (err) { console.error('i18next 初始化失败:', err); return; } // 初始化完成后的回调 console.log(t('key')); // 输出: Hello World });
关键配置选项
语言相关
- lng: 设置默认语言(如 'en', 'zh', 'fr')
- fallbackLng: 当翻译不存在时的回退语言
- supportedLngs: 支持的语言列表
javascripti18next.init({ lng: 'zh', fallbackLng: 'en', supportedLngs: ['en', 'zh', 'fr', 'de'] });
资源相关
- resources: 直接定义翻译资源
- ns: 默认命名空间
- defaultNS: 默认使用的命名空间
javascripti18next.init({ resources: { en: { translation: { "welcome": "Welcome" }, common: { "save": "Save", "cancel": "Cancel" } } }, ns: ['translation', 'common'], defaultNS: 'translation' });
插值相关
- interpolation: 配置插值行为
javascripti18next.init({ interpolation: { escapeValue: false, // 不转义 HTML format: function(value, format, lng) { if (format === 'uppercase') return value.toUpperCase(); return value; } } });
检测相关
- detection: 语言检测配置
javascripti18next.init({ detection: { order: ['querystring', 'cookie', 'localStorage', 'navigator'], caches: ['localStorage', 'cookie'], lookupQuerystring: 'lng' } });
异步初始化
i18next.init() 返回一个 Promise,可以使用 async/await:
javascriptasync function initI18n() { try { await i18next.init({ lng: 'zh', resources: { zh: { translation: { "hello": "你好" } } } }); console.log('i18next 初始化成功'); } catch (error) { console.error('初始化失败:', error); } }
最佳实践
- 分离配置: 将 i18next 配置单独放在一个文件中
- 环境区分: 开发和生产环境使用不同配置
- 错误处理: 始终处理初始化错误
- 延迟加载: 大型应用使用延迟加载提高性能
- 类型安全: TypeScript 项目使用类型定义