Skip to content

i18n

国际方案使用 Remix i18n 实现

国际化

默认从浏览器中获取用户的 lang, 如果没有自动使用英语

ts
const lang = navigator.language

国际化影响

  • 路由
  • 菜单
  • url 地址编写
  • 翻译文件 locales/*
  • 翻译函数 t
  • location 字段。

国际化依赖

sh
pnpm install remix-i18next i18next react-i18next i18next-browser-languagedetector

npm install i18next-http-backend i18next-fs-backend

配置

ts
import type { InitOptions } from "i18next";

export default {
  supportedLngs: ["en-US", "zh-CN"],
  fallbackLng: "zh-CN",
  defaultNS: "common",
  react: { useSuspense: false },
} satisfies InitOptions;

文件位置

sh
./public/locales/{{lng}}/{{ns}}.json

定义服务

ts
import { resolve } from "node:path";

import Backend from "i18next-fs-backend";
import { RemixI18Next } from "remix-i18next/server";

import i18nConfig from "./i18n";

const remixI18Next = new RemixI18Next({
  detection: {
    supportedLanguages: i18nConfig.supportedLngs,
    fallbackLanguage: i18nConfig.fallbackLng,
  },
  i18next: {
    ...i18nConfig,
    backend: {
      loadPath: resolve("./public/locales/{{lng}}/{{ns}}.json"),
    },
  },
  plugins: [Backend],
});

export default remixI18Next;

定义国际化

ts
import { resolve } from "node:path";

import Backend from "i18next-fs-backend";
import { RemixI18Next } from "remix-i18next/server";

import i18nConfig from "./i18n";

const remixI18Next = new RemixI18Next({
  detection: {
    supportedLanguages: i18nConfig.supportedLngs,
    fallbackLanguage: i18nConfig.fallbackLng,
  },
  i18next: {
    ...i18nConfig,
    backend: {
      loadPath: resolve("./public/locales/{{lng}}/{{ns}}.json"),
    },
  },
  plugins: [Backend],
});

export default remixI18Next;

在入口文件中使用

  • entry.client.ts
  • entry.server.ts

支持语言

  • en-US
  • zh-CN

action/loader

ts
export const action = async ({ request, params }: ActionFunctionArgs) => {
  const { lang }  = params
};

export const loader = async ({ request, params }: LoaderFunctionArgs) => {
  const { lang }  = params
};

hooks

ts
import { useTranslation } from "react-i18next";

export default function AXXRoute() {
  const { t } = useTranslation();
  const { t } = useTranslation("namespace");
}

定义本地翻译文件

public\locales 中定义 json 文件。

获取翻译函数

ts
const welcome = t("welcome")
const mene = t("menu/name/space")
  • 命名空间 a/b/c/ 表示文件夹。
  • 可以在 t 中传递第二个参数。

qa

i18n 闪动问题

tsx
if (window.requestIdleCallback) {
  window.requestIdleCallback(hydrate);
} else {
  // Safari doesn't support requestIdleCallback
  // https://caniuse.com/requestidlecallback
  window.setTimeout(hydrate, 1);
}