npm
npm install node-polyglot
yarn
yarn add node-polyglot
初始化 Polyglot
const Polyglot = require('node-polyglot');
const polyglot = new Polyglot({
phrases: {
"hello": "Hello",
"hello_name": "Hello, %{name}"
},
locale: "en"
});
// 输出: Hello
console.log(polyglot.t("hello"));
// 输出: Hello, John
console.log(polyglot.t("hello_name", { name: "John" }));
切换语言
const phrases = {
en: {
"hello": "Hello",
"hello_name": "Hello, %{name}"
},
fr: {
"hello": "Bonjour",
"hello_name": "Bonjour, %{name}"
}
};
const polyglot = new Polyglot({ phrases: phrases.en });
console.log(polyglot.t("hello")); // 输出: Hello
// 切换到法语
polyglot.replace(phrases.fr);
console.log(polyglot.t("hello")); // 输出: Bonjour
Polyglot({ phrases, locale }):初始化 Polyglot 实例。
phrases
:一个对象,包含翻译字符串。locale
:当前语言环境(可选)。polyglot.t(key, options):翻译指定的 key。
key
:要翻译的字符串的 key。options
:包含占位符替换的对象。polyglot.extend(phrases):添加新的翻译字符串。
phrases
:包含新翻译字符串的对象。polyglot.replace(phrases):替换现有的翻译字符串。
phrases
:包含新翻译字符串的对象。polyglot.clear():清除所有翻译字符串。
polyglot.locale([newLocale]):获取或设置当前语言环境。
newLocale
:要设置的新语言环境(可选)。处理复数形式
const polyglot = new Polyglot({
phrases: {
"num_cars": "%{smart_count} car |||| %{smart_count} cars"
}
});
console.log(polyglot.t("num_cars", { smart_count: 1 })); // 输出: 1 car
console.log(polyglot.t("num_cars", { smart_count: 2 })); // 输出: 2 cars
动态加载翻译文件
async function loadLocale(locale) {
const response = await fetch(`/locales/${locale}.json`);
const phrases = await response.json();
polyglot.replace(phrases);
}
loadLocale('fr');