{"id":18687890,"url":"https://github.com/yxw007/translate","last_synced_at":"2026-04-04T06:14:36.816Z","repository":{"id":255469464,"uuid":"848053524","full_name":"yxw007/translate","owner":"yxw007","description":"🎉一个简单的翻译库，支持多翻译引擎。A simple translation library that supports multiple translation engines","archived":false,"fork":false,"pushed_at":"2025-06-01T11:07:44.000Z","size":283,"stargazers_count":16,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-01T20:12:16.710Z","etag":null,"topics":["amazon","azure","baidu","browser","cjs","deepl","ems","google","i18n","nodejs","translate","translator","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yxw007.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["yxw007"]}},"created_at":"2024-08-27T03:30:43.000Z","updated_at":"2025-06-01T11:07:48.000Z","dependencies_parsed_at":"2024-09-05T15:39:31.939Z","dependency_job_id":"7724f03a-9f81-4dac-ac0d-669c6cfdcff4","html_url":"https://github.com/yxw007/translate","commit_stats":null,"previous_names":["yxw007/translate"],"tags_count":33,"template":false,"template_full_name":null,"purl":"pkg:github/yxw007/translate","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxw007%2Ftranslate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxw007%2Ftranslate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxw007%2Ftranslate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxw007%2Ftranslate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yxw007","download_url":"https://codeload.github.com/yxw007/translate/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yxw007%2Ftranslate/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260470344,"owners_count":23014207,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["amazon","azure","baidu","browser","cjs","deepl","ems","google","i18n","nodejs","translate","translator","typescript"],"created_at":"2024-11-07T10:34:42.693Z","updated_at":"2026-04-04T06:14:36.810Z","avatar_url":"https://github.com/yxw007.png","language":"TypeScript","funding_links":["https://github.com/sponsors/yxw007"],"categories":[],"sub_categories":[],"readme":"# Translate\n\nEnglish | [简体中文](./README_zh-CN.md)\n\n![GitHub top language](https://img.shields.io/github/languages/top/yxw007/translate)\n![GitHub License](https://img.shields.io/github/license/yxw007/translate)\n![NPM Version](https://img.shields.io/npm/v/%40yxw007%2Ftranslate)\n![Codecov](https://codecov.io/gh/yxw007/translate/branch/master/graph/badge.svg)\n![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/yxw007/translate/ci.yml)\n\n## ❓ Why do I need translate?\n\n1. a lot of translation tool libraries on the market, basically not very well-maintained\n2. not written by ts, not friendly enough when using the prompts\n3. single function, does not support batch translation Or only support a translation engine\n4. ...\n\n\u003e Note: Translate helps you to solve all the above problems, and will expand more in the future!\n\n## ✨ Features\n\n- 🌐 **Multi-environment support**: Node environment, browser environment\n- ✨ **Easy to use**: provides a concise API, you can easily help you to translate\n- 🌍 **Multi-translation engine support**: Google, Azure Translate, Amazon Translate, Deepl, Baidu, OpenAI, etc. (will expand more in the future)\n- 🛠️ **typescript**: friendlier code hints and quality assurance\n- 📦 **Batch translation**: one api request, translate more content, reduce http requests to improve translation efficiency\n- 🔓 **completely open source**.\n\n\u003e **Special reminder: although the library has supported the use of the browser environment, but please only use the google engine translation (google does not need key), the use of other translation engine need to configure the key, the use of the front-end will lead to key leakage, do not do it**\n\n\u003e Browser bundles exclude Node-only helpers such as filesystem utilities. Keep browser usage focused on engines that are safe to expose client-side.\n\n## 💻Translation engines, integration cases\n\n| Name             | Support | Description                                                                                                                                               |\n| ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| google           | ✔       | Commissioned and ready for use                                                                                                                            |\n| azure translate  | ✔       | Commissioned and ready for use                                                                                                                            |\n| amazon translate | ✔       | Commissioned and ready for use                                                                                                                            |\n| baidu            | ✔       | Commissioned and ready for use                                                                                                                            |\n| deepl            | ✔       | Commissioned and ready for use                                                                                                                            |\n| openai           | ✔       | Commissioned and ready for use                                                                                                                            |\n| tencent          | ✔       | Commissioned and ready for use                                                                                                                            |\n| yandex           |         | I have not tuned in as I do not have a bank account supported by the platform (help from those who are in a position to do so is welcome and appreciated) |\n\n## 🛠 Development\n\nThis project now uses `rolldown`, `oxlint`, and `oxfmt` instead of `rollup`, `eslint`, and `prettier`.\n\n```bash\npnpm build\npnpm lint\npnpm lint:fix\npnpm format\npnpm format:check\npnpm test\n```\n\n- `pnpm build`: builds Node and browser bundles with `rolldown`, then emits `.d.ts` files with TypeScript.\n- `pnpm lint`: runs `oxlint` and `oxfmt --check`.\n- `pnpm lint:fix`: applies `oxlint --fix` and formats files with `oxfmt`.\n- `pnpm format`: formats the repository with `oxfmt`.\n- `pnpm test`: runs stable offline-safe tests.\n\nIntegration tests that require real network access and third-party credentials are disabled by default. To run them manually, set `RUN_INTEGRATION_TESTS=true` before running `pnpm test`.\n\n- Bash\n\n  ```bash\n  RUN_INTEGRATION_TESTS=true pnpm test\n  ```\n\n- PowerShell\n\n  ```powershell\n  $env:RUN_INTEGRATION_TESTS = \"true\"\n  pnpm test\n  ```\n\n## 🚀 Install\n\n- npm\n\n  ```bash\n  npm install @yxw007/translate\n  ```\n\n- yarn\n\n  ```bash\n  yarn add @yxw007/translate\n  ```\n\n- pnpm\n\n  ```bash\n  pnpm i @yxw007/translate\n  ```\n\n## 📖 Usage\n\n### Node\n\n- ESM\n\n  ```typescript\n  import { translator, engines } from \"@yxw007/translate\";\n  ```\n\n- Commonjs\n\n  ```typescript\n  const { translator, engines } = required(\"@yxw007/translate\");\n  ```\n\n- Translation examples\n\n  ```typescript\n  translator.addEngine(engines.google);\n  const res1 = await translator.translate(\"hello\", { from: \"en\", to: \"zh\" });\n  console.log(res1);\n\n  const res2 = await translator.translate([\"hello\", \"good\"], { from: \"en\", to: \"zh\", engine: \"google\" });\n  console.log(res2);\n  ```\n\n  Output results\n\n  ```bash\n  ['你好']\n  [\"你好\", \"好的\"]\n  ```\n\n- Language detection examples\n\n  ```typescript\n  translator.addEngine(engines.google);\n  const res1 = await translator.checkLanguage(\"hello\", { engine: \"google\" });\n  console.log(res1);\n  ```\n\n  Output results\n\n  ```bash\n  en\n  ```\n\n### Browser\n\nuse jsDelivr CDN\n\n- `development`\n\n  ```html\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.js\"\u003e\u003c/script\u003e\n  ```\n\n- `production`\n\n  ```html\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.min.js\"\u003e\u003c/script\u003e\n  ```\n\n- example\n\n  ```html\n  \u003c!DOCTYPE html\u003e\n  ...\n\n  \u003chead\u003e\n    ...\n    \u003cscript src=\"https://cdn.jsdelivr.net/npm/@yxw007/translate@0.0.7/dist/browser/index.umd.js\"\u003e\u003c/script\u003e\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n    \u003cscript\u003e\n      (async () =\u003e {\n        const { engines, translator } = translate;\n        translator.addEngine(engines.google);\n        const res = await translator.translate(\"hello\", { from: \"en\", to: \"zh\" });\n        console.log(res);\n      })();\n    \u003c/script\u003e\n  \u003c/body\u003e\n\n  \u003c/html\u003e\n\n  ```\n\n## 📚 API\n\n### Translator\n\n```typescript\nclass Translator {\n  private engines: Map\u003cstring, Engine\u003e;\n  constructor() {\n    this.engines = new Map\u003cstring, Engine\u003e();\n  }\n  /**\n   * This method is obsolete, please use the addEngine method\n   * @param engine {@link Engine}  instance\n   * @deprecated Use {@link addEngine} instead.\n   */\n  use(engine: Engine) {\n    this.addEngine(engine);\n  }\n  addEngine(engine: Engine) {\n   ...\n  }\n  removeEngine(engineName: string) {\n   ...\n  }\n  getFromLanguages(engineName: string) {\n   ...\n  }\n  getToLanguages(engineName: string) {\n   ...\n  }\n  translate\u003cT extends Engines\u003e(text: string | string[], options: TranslateOptions\u003cT\u003e) {\n    ...\n  }\n}\n```\n\n#### `use`\n\nAdd a translation engine to transitorion engine to translator\n\n```typescript\ntype Engine = {\n  name: string;\n  getFromLanguages(): Record\u003cstring, string\u003e;\n  getToLanguages(): Record\u003cstring, string\u003e;\n  normalFromLanguage(language?: string): string;\n  normalToLanguage(language?: string): string;\n  translate(text: string | string[], options: EngineTranslateOptions) {\n};\n```\n\n#### `translate`\n\nYou can pass a text or pass a text array, which will return a translated `Promise\u003cstring[]\u003e`\n\n```typescript\ntranslate\u003cT extends Engines\u003e(text: string | string[], options: TranslateOptions\u003cT\u003e)\n```\n\n#### `getFromLanguages` / `getToLanguages`\n\nRead the language list for the specified engine.\n\n```typescript\ntranslator.getFromLanguages(\"google\");\ntranslator.getToLanguages(\"google\");\n```\n\n#### TranslateOptions\n\n```typescript\nexport interface TranslateOptions {\n  from?: FromLanguage\u003cT\u003e;\n  to: ToLanguage\u003cT\u003e;\n  engine?: Engines;\n  /**\n   * Cache time in milliseconds\n   */\n  cache_time?: number;\n  /**\n   * Domain to use for translation\n   */\n  domain?: string;\n}\n```\n\n\u003e Note: Each engine now maintains its own `from`/`to` language configuration. You can inspect the engine-scoped configuration under `src/language/engines/*`.\n\n### Each translation of Engine's Option\n\n#### BaseEngineOption\n\n```typescript\ninterface BaseEngineOption {\n  fromLanguages?: Record\u003cstring, string\u003e;\n  toLanguages?: Record\u003cstring, string\u003e;\n}\n```\n\n\u003e `fromLanguages` / `toLanguages` are only initialization options for engine factories that need custom language tables. They are not exposed as public fields on the engine instance.\n\n#### Custom Engine\n\n```typescript\nimport { Translator, type Engine } from \"@yxw007/translate\";\n\nconst translator = new Translator();\n\nconst fromLanguages = { Auto: \"auto\", English: \"en\" };\nconst toLanguages = { Chinese: \"zh\", Japanese: \"ja\" };\n\nconst customEngine: Engine = {\n  name: \"custom\",\n  getFromLanguages() {\n    return fromLanguages;\n  },\n  getToLanguages() {\n    return toLanguages;\n  },\n  normalFromLanguage(language) {\n    if (!language || language === \"auto\") return \"auto\";\n    return fromLanguages[language as keyof typeof fromLanguages] ?? \"\";\n  },\n  normalToLanguage(language) {\n    if (!language) return \"\";\n    return toLanguages[language as keyof typeof toLanguages] ?? \"\";\n  },\n  async translate(text, options) {\n    const list = Array.isArray(text) ? text : [text];\n    return list.map((item) =\u003e `[${options.from}-\u003e${options.to}] ${item}`);\n  },\n};\n\ntranslator.addEngine(customEngine);\n```\n\nBuilt-in engines are directly referenced:\n\n```typescript\ntranslator.addEngine(engines.google);\n```\n\n#### AzureEngineOption\n\n```typescript\ninterface AzureEngineOption extends BaseEngineOption {\n  key: string;\n  region: string;\n}\n```\n\n\u003e Note: Option Param, please get it from the corresponding platform\n\n- Relative document：[rest-api-guide](https://learn.microsoft.com/zh-cn/azure/ai-services/translator/reference/rest-api-guide?WT.mc_id=Portal-Microsoft_Azure_ProjectOxford)\n\n#### AmazonEngineOption\n\n```typescript\ninterface AmazonEngineOption extends BaseEngineOption {\n  region: string;\n  accessKeyId: string;\n  secretAccessKey: string;\n}\n```\n\n\u003e Note: Option Param, please get it from the corresponding platform\n\n- Related document：https://docs.aws.amazon.com/translate/latest/dg/what-is.html\n- Related library：https://www.npmjs.com/package/@aws-sdk/client-translate\n\n#### BaiduEngineOption\n\n```typescript\nexport interface BaiduEngineOption extends BaseEngineOption {\n  appId: string;\n  secretKey: string;\n}\n```\n\n\u003e Note: Option Param, please get it from the corresponding platform\n\n- Related document：https://fanyi-api.baidu.com/product/121\n\n#### DeeplEngineOption\n\n```typescript\nexport interface DeeplEngineOption {\n  key: string;\n}\n```\n\n\u003e Note: Option Param, please get it from the corresponding platform\n\n- Related document：https://www.deepl.com/en/your-account/keys\n\n#### OpenAIEngineOption\n\n```typescript\nexport interface OpenAIEngineOption {\n  apiKey: string;\n  model: OpenAIModel;\n}\n\nexport const OPEN_AI_MODELS = [\n  \"o1-preview\",\n  \"o1-preview-2024-09-12\",\n  \"o1-mini-2024-09-12\",\n  \"o1-mini\",\n  \"dall-e-2\",\n  \"gpt-3.5-turbo\",\n  \"gpt-3.5-turbo-0125\",\n  \"babbage-002\",\n  \"davinci-002\",\n  \"dall-e-3\",\n  \"text-embedding-3-large\",\n  \"gpt-3.5-turbo-16k\",\n  \"tts-1-hd-1106\",\n  \"text-embedding-ada-002\",\n  \"text-embedding-3-small\",\n  \"tts-1-hd\",\n  \"whisper-1\",\n  \"gpt-3.5-turbo-1106\",\n  \"gpt-3.5-turbo-instruct\",\n  \"gpt-4o-mini-2024-07-18\",\n  \"gpt-4o-mini\",\n  \"tts-1\",\n  \"tts-1-1106\",\n  \"gpt-3.5-turbo-instruct-0914\",\n] as const;\n\nexport type OpenAIModel = (typeof OPEN_AI_MODELS)[number];\n```\n\n\u003e Description：option param Please get it from the corresponding platform.\n\n- Related document：https://platform.openai.com/settings/organization/api-keys\n\n#### TencentEnginOption\n\n```typescript\nexport interface TencentEngineOption extends BaseEngineOption {\n  secretId: string;\n  secretKey: string;\n  region?: string;\n}\n```\n\n\u003e Description: Option Param Please obtain it from the corresponding platform.\n\n- Related documentation：https://console.cloud.tencent.com/cam/capi\n\n- Region Configuration table\n  | 地域 | 取值 |\n  | ---------------------- | ---------------- |\n  | 亚太东南（曼谷） | ap-bangkok |\n  | 华北地区（北京） | ap-beijing |\n  | 西南地区（成都） | ap-chengdu |\n  | 西南地区（重庆） | ap-chongqing |\n  | 华南地区（广州） | ap-guangzhou |\n  | 港澳台地区（中国香港） | ap-hongkong |\n  | 亚太东北（首尔） | ap-seoul |\n  | 华东地区（上海） | ap-shanghai |\n  | 华东地区（上海金融） | ap-shanghai-fsi |\n  | 华南地区（深圳金融） | ap-shenzhen-fsi |\n  | 亚太东南（新加坡） | ap-singapore |\n  | 亚太东北（东京） | ap-tokyo |\n  | 欧洲地区（法兰克福） | eu-frankfurt |\n  | 美国东部（弗吉尼亚） | na-ashburn |\n  | 美国西部（硅谷） | na-siliconvalley |\n\n## 🤝 Contribute\n\n\u003e Special attention: Please create a new branch based on the master, develop on the new branch, and create PR to Master after development.\n\n- Installation dependence\n\n  ```bash\n  pnpm install\n  ```\n\n- Add new Engine\n  - Add a new platform ENGINE plugin\n\n    ```typescript\n    export interface XXEngineOption extends BaseEngineOption {\n      key: string;\n    }\n\n    export function xx(options: XXEngineOption): Engine {\n      const { key } = options;\n      const base = \"https://translate.yandex.net/api/v1.5/tr.json/translate\";\n      return {\n        name: \"yandex\",\n        async checkLanguage\u003cT extends Engines\u003e(text: string): Promise\u003cstring\u003e {\n          //TODO: This can be done with translate, in which case the target language configuration is reused.\n        },\n        async translate\u003cT extends Engines\u003e(text: string | string[], opts: EngineTranslateOptions\u003cT\u003e) {\n          const { from, to } = opts;\n          if (!Array.isArray(text)) {\n            text = [text];\n          }\n          //TODO: Call the platform translation APIplatform translation API\n          const translations: string[] = [];\n          //TODO: Analyze the corresponding results of the platform API, and resolve the results to the translations back\n          for (const translation of body.text) {\n            if (translation) {\n              translations.push(translation);\n            }\n          }\n          return translations;\n        },\n      };\n    }\n    ```\n\n  - Add the plugin to Engines(Location:`/src/engines/index.ts`)\n\n    ```typescript\n    import { xx } from \"./xx\";\n    export const engines = {\n      google,\n      azure,\n      amazon,\n      baidu,\n      deepl,\n      openai,\n      xx,\n    } as const;\n    ```\n\n  - Add the origin language configuration supported by the engine\n\n    ```typescript\n    //Note: If the origin and target languages are the same, you can directly use the target language to configure them, otherwise please configure them separately\n    //src/language/origin/index.ts\n    import azure from \"../target/azure\";\n    ...\n    import xxx from \"../target/xxx\"\n\n    export const originLanguages = {\n      azure: azure,\n      ...\n      xxx: xxx,\n    } as const;\n\n    export type originLanguageMapNames = {\n      amazon: keyof typeof amazon;\n      ...\n      xxx: keyof typeof xxx;\n    };\n\n    export type originLanguageMapValues = {\n      amazon: ValuesOf\u003ctypeof amazon\u003e;\n      ...\n      xxx: ValuesOf\u003ctypeof xxx\u003e;\n    };\n\n    ```\n\n  - Add the target language that is supported by the engine\n\n    ```typescript\n    //src/language/target/index.ts\n    import azure from \"./azure\";\n    ...\n    import xxx from \"./amazon\";\n\n    export const targetLanguages = {\n      azure: azure,\n      ...\n      xxx: xxx,\n    } as const;\n\n    export type targetLanguageMapNames = {\n      amazon: keyof typeof amazon;\n      ...\n      xxx: keyof typeof xxx;\n    };\n\n    export type targetLanguageMapValues = {\n      amazon: ValuesOf\u003ctypeof amazon\u003e;\n      ...\n      xxx: ValuesOf\u003ctypeof xxx\u003e;\n    };\n    ```\n\n- Build\n\n  ```bash\n  pnpm build\n  ```\n\n- Test\n  ```bash\n  pnpm test\n  ```\n\n\u003e **Tips: At present, the library can be used normally. Welcome everyone to experience. If you have any questions and suggestions, you can mention the feedback to me.If you are interested, you are welcome to join, let us improve this tool together. Help to click star ⭐, let more people know this tool, thank you for everyone🙏**\n\n## 🌹 Thanks\n\n- [franciscop/translate](https://github.com/franciscop/translate.git)\n\n\u003e Note：Thanks to [franciscop/translate](https://github.com/franciscop/translate.git) for giving me ideas for a quick implementation of this library, and also indirectly some of his code. Much appreciated.🙏\n\n## 📄 License\n\nTranslate is released under the MIT license. See the [`LICENSE`](./LICENSE) file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyxw007%2Ftranslate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyxw007%2Ftranslate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyxw007%2Ftranslate/lists"}