npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@yxw007/translate

v0.0.20

Published

A simple library that supports multiple translation engines

Downloads

651

Readme

Translate

English | 简体中文

GitHub top language GitHub License NPM Version Codecov GitHub Actions Workflow Status

❓ Why do I need translate?

  1. a lot of translation tool libraries on the market, basically not very well-maintained
  2. not written by ts, not friendly enough when using the prompts
  3. single function, does not support batch translation Or only support a translation engine
  4. ...

Note: Translate helps you to solve all the above problems, and will expand more in the future!

✨ Features

  • 🌐 Multi-environment support: Node environment, browser environment
  • Easy to use: provides a concise API, you can easily help you to translate
  • 🌍 Multi-translation engine support: Google, Azure Translate, etc. (will expand more in the future)
  • 🛠️ typescript: friendlier code hints and quality assurance
  • 📦 Batch translation: one api request, translate more content, reduce http requests to improve translation efficiency
  • 🔓 completely open source.

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

💻Translation engines, integration cases

| Name | Support | Description | | ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | google | √ | Commissioned and ready for use | | azure translate | √ | Commissioned and ready for use | | amazon translate | √ | Commissioned and ready for use | | baidu | √ | Commissioned and ready for use | | deepl | √ | Commissioned and ready for use | | 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) |

🚀 Install

  • npm

    npm install @yxw007/translate
  • yarn

    yarn add @yxw007/translate
  • pnpm

    pnpm i @yxw007/translate

📖 Usage

Node

  • ESM

    import { translator, engines } from "@yxw007/translate"
  • Commonjs

    const { translator, engines }  = required("@yxw007/translate")
  • example

    translator.use(engines.google());
    const res1 = await translator.translate("hello", { from: "en", to: "zh" });
    console.log(res1);
    
    const res2 = await translator.translate(["hello", "good"], { from: "en", to: "zh", engine: "google" });
    console.log(res2);

    输出结果

    ['你好']
    ["你好", "好的"]

Browser

use jsDelivr CDN

  • development

    <script src="https://cdn.jsdelivr.net/npm/@yxw007/[email protected]/dist/browser/index.umd.js"></script>
  • production

    <script src="https://cdn.jsdelivr.net/npm/@yxw007/[email protected]/dist/browser/index.umd.min.js"></script>
  • example

    <!DOCTYPE html>
    ...
    
    <head>
      ...
      <script src="https://cdn.jsdelivr.net/npm/@yxw007/[email protected]/dist/browser/index.umd.js"></script>
    </head>
    
    <body>
      <script>
        (async () => {
          const { engines, translator } = translate;
          translator.use(engines.google());
          const res = await translator.translate("hello", { from: "en", to: "zh" });
          console.log(res);
        })();
      </script>
    </body>
    
    </html>
    

📚 API

Translator

class Translator {
  private engines: Map<string, Engine>;
  constructor() {
    this.engines = new Map<string, Engine>();
  }
  use(engine: Engine) {
   ...
  }
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
    ...
  }
}

use

Add a translation engine to transitorion engine to translator

type Engine = {
  name: string;
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
};

translate

You can pass a text or pass a text array, which will return a translated Promise<string[]>

translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>)

TranslateOptions

export interface TranslateOptions {
  from?: FromLanguage<T>;
  to: ToLanguage<T>;
  engine?: Engines;
   /**
   * Cache time in milliseconds
   */
  cache_time?: number;
  /**
   * Domain to use for translation
   */
  domain?: string;
}

Note: To learn more about the support of each engine language, go to the following directory to view the corresponding configurations

Each translation of Engine's Option

BaseEngineOption

interface BaseEngineOption {}

AzureEngineOption

interface AzureEngineOption extends BaseEngineOption {
  key: string;
  region: string;
}

Note: Option Param, please get it from the corresponding platform

AmazonEngineOption

interface AmazonEngineOption extends BaseEngineOption{
  region: string;
  accessKeyId: string;
  secretAccessKey: string;
}

Note: Option Param, please get it from the corresponding platform

  • Related document:https://docs.aws.amazon.com/translate/latest/dg/what-is.html
  • Related library:https://www.npmjs.com/package/@aws-sdk/client-translate

BaiduEngineOption

export interface BaiduEngineOption extends BaseEngineOption {
  appId: string;
  secretKey: string;
}

Note: Option Param, please get it from the corresponding platform

  • Related document:https://fanyi-api.baidu.com/product/121

DeeplEngineOption

export interface DeeplEngineOption {
  key: string;
}

Note: Option Param, please get it from the corresponding platform

  • Related document:https://www.deepl.com/en/your-account/keys

🤝 Contribute

Special attention: Please create a new branch based on the master, develop on the new branch, and create PR to Master after development.

  • Installation dependence

    pnpm install
  • Add new Engine

    • Add a new platform ENGINE plugin

      export interface XXEngineOption extends BaseEngineOption {
        key: string;
      }
      
      export function xx(options: XXEngineOption): Engine {
        const { key } = options;
        const base = "https://translate.yandex.net/api/v1.5/tr.json/translate";
        return {
          name: "yandex",
          async translate<T extends Engines>(text: string | string[], opts: EngineTranslateOptions<T>) {
            const { from, to } = opts;
            if (!Array.isArray(text)) {
              text = [text];
            }
            //TODO: Call the platform translation APIplatform translation API
            const translations: string[] = [];
            //TODO: Analyze the corresponding results of the platform API, and resolve the results to the translations back
            for (const translation of body.text) {
              if (translation) {
                translations.push(translation);
              }
            }
            return translations;
          },
        };
      }
    • Add the plugin to Engines(Location:/src/engines/index.ts)

      import { xx } from "./xx";
      export const engines = {
        google,
        azure,
        amazon,
        baidu,
        deepl,
        xx
      } as const;
    • Add the origin language configuration supported by the engine

      //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
      //src/language/origin/index.ts  
      import azure from "../target/azure";
      ...
      import xxx from "../target/xxx"
          
      export const originLanguages = {
        azure: azure,
        ...
        xxx: xxx,
      } as const;
      
      export type originLanguageMapNames = {
        amazon: keyof typeof amazon;
        ...
        xxx: keyof typeof xxx;
      };
      
      export type originLanguageMapValues = {
        amazon: ValuesOf<typeof amazon>;
        ...
        xxx: ValuesOf<typeof xxx>;
      };
      
    • Add the target language that is supported by the engine

      //src/language/target/index.ts  
      import azure from "./azure";
      ...
      import xxx from "./amazon";
      
      export const targetLanguages = {
        azure: azure,
        ...
        xxx: xxx,
      } as const;
      
      export type targetLanguageMapNames = {
        amazon: keyof typeof amazon;
        ...
        xxx: keyof typeof xxx;
      };
      
      export type targetLanguageMapValues = {
        amazon: ValuesOf<typeof amazon>;
        ...
        xxx: ValuesOf<typeof xxx>;
      };
      
  • Build

    pnpm build
  • Test

    pnpm test

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🙏

🌹 Thanks

Note:Thanks to franciscop/translate for giving me ideas for a quick implementation of this library, and also indirectly some of his code. Much appreciated.🙏

📄 License

Translate is released under the MIT license. See the LICENSE file.