ttag 项目使用教程
项目介绍
ttag
是一个基于 ES6 标签模板的现代 JavaScript i18n 本地化库。它允许开发者通过简单的标签将字符串标记为可翻译的,并提供了丰富的功能,如复数、上下文、翻译注释等。ttag
使用 GNU gettext 格式,这是一个简单且生态丰富的本地化格式。
项目快速启动
安装
首先,你需要安装 ttag
及其命令行工具:
npm install ttag ttag-cli --save-dev
基本使用
在你的 JavaScript 文件中,你可以使用 t
函数来标记可翻译的字符串:
import { t } from 'ttag';
console.log(t`This string will be translated`);
提取翻译
使用 ttag-cli
工具提取所有标记的字符串到 .po
文件:
ttag extract index.js -o translations.po
更新翻译
更新 .po
文件中的翻译:
ttag update translations.po index.js
替换翻译
将源文件中的字符串替换为翻译后的字符串:
ttag replace translations.po index.js -o index-translated.js
应用案例和最佳实践
复数处理
使用 ngettext
函数处理复数形式的翻译:
import { ngettext, msgid } from 'ttag';
const count = 5;
console.log(ngettext(msgid`${count} banana`, `${count} bananas`, count));
上下文
使用 c
函数为翻译添加上下文:
import { c, t } from 'ttag';
console.log(c('email').t`This text will be in email context`);
JSX 支持
在 JSX 中使用 jt
函数:
import { jt } from 'ttag';
const element = <div>JSX Element</div>;
console.log(jt`Can use ${element} inside the translations`);
典型生态项目
ttag
可以与多种生态项目集成,例如:
- Babel: 使用
babel-plugin-ttag
插件提取字符串。 - TypeScript: 支持
.ts
和.tsx
文件。 - React: 在 React 项目中无缝使用。
通过这些集成,ttag
可以轻松地融入几乎任何工作流程中,提供高效的本地化支持。