react-i18next 使用代码

125 阅读1分钟

背景

记录一下 react-i18next 的一些使用方式代码,方便以后再次使用等等

安装

  1. 安装react-i18next:在项目目录中运行以下命令来安装react-i18next和i18next:
npm install react-i18next i18next

代码

如下

import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";

import * as en from "./en";
import * as ja from "./ja";
import * as zh from "./zh";

export const translations = { en, zh, ja };



export const defaultNS = "general";

export async function initI18n(options){
  const { context = "browser" } = options;
  if (context === "browser") {
    i18n.use(initReactI18next);
    i18n.use(LanguageDetector);
  }
  await i18n.init({
    resources: translations,
    detection:
      context === "browser"
        ? { order: ["localStorage", "navigator"], caches: ["localStorage"] }
        : undefined,
    fallbackLng: "en",
    defaultNS,
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
  });
}