一个可读、自动化且经过优化的(2 kb)国际化方案,适用于 JavaScript
npm install @lingui/core @lingui/react
npm install --save-dev @lingui/cliLingui 宏在构建时运行,因此请为你的转译器添加宏插件,并创建一个 lingui.config.js。安装指南 会在几分钟内介绍这两项内容。
然后,将你想要翻译的文本包裹在 Trans 宏中。无需发明消息 ID,也无需维护单独的 JSON 文件来保持同步:
import { i18n } from "@lingui/core"
import { I18nProvider } from "@lingui/react"
import { Trans } from "@lingui/react/macro"
import { messages } from "./locales/en/messages"
i18n.load("en", messages)
i18n.activate("en")
export function App() {
return (
<I18nProvider i18n={i18n}>
<Trans>
Read the <a href="https://lingui.dev">documentation</a> for more info.
</Trans>
</I18nProvider>
)
}将消息提取到 PO 目录中,进行翻译,然后将目录编译为优化后的运行时输出:
npx lingui extract
npx lingui compile翻译完成后,src/locales/cs/messages.po 中的捷克语目录如下所示。<0> 标签代表 <a> 元素,因此翻译人员无需接触你的标记:
#: src/App.jsx:12
msgid "Read the <0>documentation</0> for more info."
msgstr "Přečtěte si <0>dokumentaci</0> pro více informací."继续阅读 React 教程,或跳转到 React Server Components、React Native、SolidJS 或纯 JavaScript。Vite、Next.js、Remix、TanStack Start、React Native 等的可用项目位于 examples 目录中。
在基于 key 的 i18n 库中,你需要发明一个 key,把文本放在 JSON 文件里,然后在代码中引用这个 key。而使用 Lingui,文本会保留在它被阅读的地方:
// 基于 key 的 i18n:代码持有 key,文本存放在别处
<h1>{t("dashboard.welcome.title")}</h1>
// Lingui:文本是唯一可信源,目录(catalog)是生成的暂无开放 Issues,或尚未同步最近议题。