JavaScript SDK

Lingo.dev JavaScript SDK 为 Web 应用程序、Node.js 服务器和前端框架添加了实时 AI 驱动的翻译功能。该 SDK 处理动态内容,例如聊天消息、用户评论和需要即时翻译的实时数据。

与使用 Lingo.dev CLI 的静态文件本地化不同,SDK 按需处理内容,非常适合聊天应用程序、电子邮件客户端和内容不断变化的社交媒体工具。

安装

npm install lingo.dev

基本设置

import { LingoDotDevEngine } from "lingo.dev/sdk";

const lingoDotDev = new LingoDotDevEngine({
  apiKey: "your-api-key-here",
});

文本翻译

翻译简单文本:

const result = await lingoDotDev.localizeText("Hello, world!", {
  sourceLocale: "en",
  targetLocale: "es",
});
// 返回: "¡Hola Mundo!"

翻译为多种语言:

const results = await lingoDotDev.batchLocalizeText("Hello, world!", {
  sourceLocale: "en",
  targetLocales: ["es", "fr", "de"],
});
// 返回: ['¡Hola Mundo!', 'Bonjour le monde!', 'Hallo Welt!']

对象翻译

翻译结构化数据:

const content = {
  greeting: "Hello",
  farewell: "Goodbye",
  message: "Welcome to our platform",
};

const translated = await lingoDotDev.localizeObject(content, {
  sourceLocale: "en",
  targetLocale: "es",
});
// 返回: { greeting: "Hola", farewell: "Adiós", message: "Bienvenido a nuestra plataforma" }

此方法处理嵌套对象并在翻译文本值的同时保留原始结构。

聊天翻译

翻译对话数组:

const conversation = [
  { name: "Alice", text: "Hello!" },
  { name: "Bob", text: "How are you?" },
  { name: "Alice", text: "I'm doing well, thanks!" },
];

const translated = await lingoDotDev.localizeChat(conversation, {
  sourceLocale: "en",
  targetLocale: "es",
});
// 返回翻译后的对话,结构保持不变

聊天方法保留了用户名等元数据,同时仅翻译文本内容。

HTML 翻译

在保留标记的同时翻译 HTML:

const html = "<div>Hello <strong>world</strong></div>";

const translated = await lingoDotDev.localizeHtml(html, {
  sourceLocale: "en",
  targetLocale: "es",
});
// 返回: "<div>Hola <strong>mundo</strong></div>"

HTML 翻译在仅翻译文本内容的同时,保留所有标签、属性和结构。

语言检测

自动检测源语言:

const locale = await lingoDotDev.recognizeLocale("Bonjour le monde");
// 返回: 'fr'

结合自动检测使用:

const result = await lingoDotDev.localizeText("Bonjour le monde", {
  sourceLocale: null, // 自动检测
  targetLocale: "en",
});
// 返回: "Hello world"

语言检测会增加处理时间,因此仅在源语言未知时使用。

配置选项

配置 SDK 行为:

const lingoDotDev = new LingoDotDevEngine({
  apiKey: "your-api-key-here",
  batchSize: 100, // 每次 API 请求的最大项目数(默认: 50,最大: 250)
  idealBatchItemSize: 1000, // 每批目标字数(默认: 500,最大: 2500)
});

批量大小 控制每次 API 请求发送的项目数量。较高的值可以减少 API 调用次数,但会增加请求大小。

理想批量项目大小 控制目标字数以实现最佳处理效率。

翻译参数

速度与质量控制:

const result = await lingoDotDev.localizeText("Hello world", {
  sourceLocale: "en",
  targetLocale: "es",
  fast: true, // 优先速度而非质量
});

fast 参数允许在时间敏感的应用中以较快的速度进行翻译,但可能会降低质量。

进度跟踪

监控大型翻译任务:

await lingoDotDev.localizeObject(
  largeObject,
  { sourceLocale: "en", targetLocale: "es" },
  (progress) => {
    console.log(`翻译进度: ${progress}%`);
    // 更新 UI 进度条
  },
);

进度回调为大型翻译操作提供实时反馈,这对于用户界面更新非常有用。

错误处理

实施适当的错误处理:

try {
  const result = await lingoDotDev.localizeText("Hello", {
    sourceLocale: "en",
    targetLocale: "es",
  });
} catch (error) {
  console.error("Translation failed:", error.message);
  // 适当处理错误
}

SDK 包含针对网络问题的自动重试功能,但应用级别的错误处理仍然非常重要。