Polyglot.js

2024-06-27 09:59:51 144
Polyglot.js 是一个轻量级的国际化 (i18n) 库,用于在 JavaScript 应用程序中简化语言和区域的处理。它提供了一种简单的 API,帮助开发者轻松地实现字符串的多语言支持和翻译功能,特别适合小型项目或需要快速实现国际化的应用。

特点

  1. 轻量级:核心库只有几KB,非常适合性能敏感的应用。
  2. 简单易用:API 设计简洁,易于上手和集成。
  3. 灵活性:支持简单的占位符替换和复数形式处理。
  4. 可扩展:允许开发者根据需要扩展和自定义功能。

使用场景

  1. 小型项目:需要快速实现多语言支持的小型项目。
  2. 前端应用:在前端应用中动态加载和切换语言。
  3. 简单翻译需求:处理简单的字符串替换和复数形式的翻译需求。

安装方式

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

常用 API 介绍

  1. Polyglot({ phrases, locale }):初始化 Polyglot 实例。

    • phrases:一个对象,包含翻译字符串。
    • locale:当前语言环境(可选)。
  2. polyglot.t(key, options):翻译指定的 key。

    • key:要翻译的字符串的 key。
    • options:包含占位符替换的对象。
  3. polyglot.extend(phrases):添加新的翻译字符串。

    • phrases:包含新翻译字符串的对象。
  4. polyglot.replace(phrases):替换现有的翻译字符串。

    • phrases:包含新翻译字符串的对象。
  5. polyglot.clear():清除所有翻译字符串。

  6. 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');

官方资料