概览

generaltranslation 库简介

介绍

generaltranslation 库是 GT 的核心 i18n 库,提供用于翻译和格式化的实用函数与类。 它通常与 gt-nextgt-react 等框架包搭配使用,也可作为独立库单独使用。

index.ts
import { GT } from 'generaltranslation';

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  sourceLocale: 'en',
  targetLocale: 'es',
});

// 翻译内容
const result = await gt.translate('Hello, world!', 'es');
// "¡Hola, mundo!"

// 格式化数字、日期和货币
const formattedPrice = gt.formatCurrency(29.99, 'USD');
const formattedDate = gt.formatDateTime(new Date());
// "$29.99"
// "9/25/2025"

// 处理语言区域设置
const localeProps = gt.getLocaleProperties('fr-CA');
const isValid = gt.isValidLocale('de');
// { language: "fr", region: "CA", ... }
// true

安装

npm install generaltranslation
yarn add generaltranslation
bun add generaltranslation
pnpm add generaltranslation

示例

翻译主要分为两类:字符串翻译和文件翻译。

设置

要启用翻译,您需要提供项目 ID 和 API key。 请参阅 constructor 方法以了解更多信息。

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  targetLocale: 'es',
});

字符串翻译

参阅 translate 方法以了解更多信息。

try {
  const result = await gt.translate('Hello, world!');
  console.log(result); // "¡Hola, mundo!"
} catch (error) {
  console.error('翻译失败:', error.message);
}

文件翻译

文件以“任务”的形式进行翻译。 上传文件即可启动一个任务。 一次上传多个文件会启动多个任务。

查看 uploadSourceFilescheckFileTranslations 方法以了解更多信息。

// 要上传的文件
const files = [
  {
    source: {
      fileName: 'src/components/Button.tsx',
      fileFormat: 'TSX',
      locale: 'en',
      content: '...',
    },
  },
];

// 上传源文件
await gt.uploadSourceFiles(files);

目录

GT 类

提供翻译与 locale 功能的主类:

翻译方法

格式化方法

Locale 方法

实用工具函数

格式化函数

Locale 函数

类型与接口

TypeScript 定义:


后续步骤

有关特定框架的用法,请参阅 Next.jsReact 文档。

这份指南怎么样?

概览