我想介绍一个我开发的替代 i18n 库。
- 适用于 Vanilla JS (
lingui-i18n) 和 React (lingui-react)
-
lingui-react 是唯一完全支持内联组件和丰富格式的库(见下文)
- 建立在 ICU MessageFormat 之上
- 还包括用于构建消息目录的 CLI (
lingui-cli)
- 它在编译时使用流类型和大量验证来捕获 MessageFormat 中的明显错误
语法
ICU MessageFormat 非常灵活,因为它支持变量、复数、序数、选择、数字/日期格式,并且还可以扩展。但是,复杂的消息编写起来有点困难。
lingui-i18n 使用 ES6 标记的模板文字提供方便的语法,而 lingui-react 使用 React 组件提供类似的语法
原版JS
import { i18n } from 'lingui-i18n'
i18n.t`Hello World`
i18n.t`Hello, my name is ${name}`
i18n.plural({ value: count, one: "# book", other: "# books" })
lingui-i18n docs中的更多示例
反应
import React from 'react'
import { Trans, Plural } from 'lingui-react'
class App extends React.Component {
render() {
const name = "Fred"
const count = 42
return (
<div>
// Static text
<Trans>January</Trans>
// Variables
<Trans>Hello, my name is {name}</Trans>
// Components
<Trans>See the <a href="/more">description</a> below.</Trans>
// Plurals
<Plural
value={count}
zero={<strong>No books</strong>}
one="# book"
other="# books"
/>
</div>
)
}
}
docs 是 js-lingui 主要文档的一部分。
内联组件和丰富的格式
我开始编写这个库是因为我想要 a) 更简单的语法和 b) 对内联组件的完全支持。
react-intl 和 react-i18next 对富文本和内联组件的支持非常有限。您可以在组件内使用基本的 html 标签 (This is <strong>bold</strong> text.) 或将组件作为变量注入 (This is {el} text. where el = <strong>bold</strong>)。
第一种方法的问题是您不能使用自定义 React 组件。第二种方法的问题是翻译器使用 2 条消息而不是 1 条消息(This is {el} text. 和 bold)。这实际上很糟糕,因为您需要翻译整个句子以保持上下文。
使用lingui-react,您可以在翻译中使用任何 React 组件,并将消息提取为一个片段:
<Trans>See the <Link to="/more">description</Link> below.</Trans>
// for translator: See the <0>description</0> below.
此解决方案的另一个优点是组件名称和道具隐藏在提取的消息中。我记得我们只在内部元素上更改了class 之后才花费大量时间更新翻译。
只需将其与 react-i18next 或 react-intl 中的插值进行比较。
要求
lingui-i18n 和 lingui-react 都需要预设才能使一切正常工作。如果您想将它与 Create React App 一起使用,这是一个问题,因为您需要弹出或分叉 react-scripts。