i18next 多语言库分析

192 阅读1分钟

基础知识

github: i18next

文档: i18next documentation

i18next是一个非常受欢迎的国际化框架,可以在浏览器或者其他js的环境(Node.js, Demo)中运行, 主要管理了多语言文件,暴露了相关api的配置,比如获取json多语言的key,还有切换lng的时候,直接将多语言切换;

主要功能:

  • 维护了翻译资源和语言/命名空间/key的对应关系;
  • 可以和后端链接,远程获取翻译内容资源;
  • 提供了优化缓存策略,可以基于localstorage等做缓存处理;
  • 提供了各类插件i18next-http-backend,i18next-browser-languagedetector, i18next-sprintf-postprocessor等;
  • ......

基本使用

import i18next from 'i18next';

i18next.init({
  lng: 'en', // if you're using a language detector, do not define the lng option
  debug: true,
  resources: {
    en: {
      translation: {
        "key": "hello world"
      }
    }
  }
});
// initialized and ready to go!
// i18next is already initialized, because the translation resources where passed via init function
document.getElementById('output').innerHTML = i18next.t('key');

基本结构

  • i18next.js :主要就是对外提供一个i18next的单例;

  • Translator.js:翻译功能的核心类,主要基于key / value来查找,内部的translator可以获取到对应的翻译内容

  • ResourceStore.js: 内部维护了翻译文件的对应和命名空间的对应关系

  • EventEmitter.js:内部就是一个常规的观察者模式,内部维护了on, off, emit钩子函数; 其他I18n,Translator, ResourceStore, Connector类都是继承了EventEmitter类;

主要类的结构关系