1.0.2 • Published 3 months ago

@spacechart/translate v1.0.2

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
3 months ago

npm version install size npm bundle size npm downloads Known Vulnerabilities

Table of Contents

Browser Support

ChromeFirefoxSafariOperaEdgeIE
Latest ✔Latest ✔Latest ✔Latest ✔Latest ✔11 ×

Installing

Package manager

Using npm:

$ npm install @spacechart/translate

Using bower:

$ bower install @spacechart/translate

Using yarn:

$ yarn add @spacechart/translate

Using pnpm:

$ pnpm add @spacechart/translate

CDN

Using jsDelivr CDN (ES5 UMD browser module):

<script src="https://cdn.jsdelivr.net/npm/@spacechart/translate@1.0.1/dist/translate.min.js"></script>

Using unpkg CDN:

<script src="https://unpkg.com/@spacechart/translate@1.0.1/dist/translate.min.js"></script>

Create Your first translate project

Initialize Node.js project

node init -y

Install dependencies

npm install @spacechart/translate

Introducing dependencies

const { DeeplxTranslateEngine, TranslateEngineInstance } = require("@spacechart/translate");

const engine = new TranslateEngineInstance(
    new DeeplxTranslateEngine({
        //...
    })
);

engine
    .translate({
        text: "你好世界"
    })
    .then((res) => {
        console.log("---翻译结果", res.data);
    });

Translate engines

开发者可以通过实现 ITranslateEngine 接口创建自定义翻译引擎,也可以使用内置的翻译引擎,比如Deeplx(DeeplxTranslateEngine

Deeplx

实现类:DeeplxTranslateEngine

const { DeeplxTranslateEngine, DeeplxLanguage } = require("@spacechart/translate");

const enine = new DeeplxTranslateEngine({
    //....
});

//发送请求
engine
    .translate({
        //....
    })
    .then((res) => {
        consoe.log("-----翻译结果", res);
    });

Custom Engine

接口类:ITranslateEngine

export class MyTranslateEngine implements ITranslateEngine {
    //单个翻译请求
    singleTranslate(options: TranslateConfigOption): Promise<TranslateResponseOption> {
        //....
    }

    //批量翻译请求
    branchTranslate(options: TranslateConfigOption[]): Promise<TranslateResponseOption[]> {
        //....
    }

    //单个或多个请求
    translate(
        options: TranslateConfigOption | TranslateConfigOption[]
    ): Promise<TranslateResponseOption> | Promise<TranslateResponseOption[]> {
        //....
    }
}

const enine = new MyTranslateEngine();

enine.translate({
    //...
});

TranslateEngineInstance Class

除了使用对应的翻译引擎类外,插件还提供了TranslateEngineInstance类,它同样继承了ITranslateEngine接口,TranslateEngineInstance 通过多态的特点,让开发者可以随意的更换引擎,而不用更改已编写的代码(如下)

Methods

方法描述
translate(options:any):Promise<any>通用翻译:传入TranslateConfigOption[]=>Promise<TranslateResponseOption[]>;传入TranslateConfigOption=>Promise<TranslateResponseOption>
singleTranslate(options: TranslateConfigOption): Promise<TranslateResponseOption>单个翻译
branchTranslate(options: TranslateConfigOption[]): Promise<TranslateResponseOption[]>批量翻译

Example

const { DeeplxTranslateEngine, TranslateEngineInstance } = require("@spacechart/translate");

const enine = new TranslateEngineInstance(
    new DeeplxTranslateEngine({
        //..
    })
    //更换引擎,下面的translate无需更换
    // new MyTranslateEngine({
    //    //..
    // })
);

enine
    .translate({
        //....
    })
    .then((res) => {
        consoe.log("-----翻译结果", res);
    });

Extention Plugins

Vue Plugin

Vue 插件通过TranslateVuePlugin类创建使用,支持v-not-translate指令排除需要翻译的文本(如下)

Options

属性类 VuePluginDefaultConfigOption

字段是否必填类型描述
engineITranslateEngine翻译引擎
elstring需要翻译的顶级节点
globalboolean是否全局注入$t全局插件变量 ,默认false

Methods

方法名描述
install(app: any, options: VuePluginDefaultConfigOption)Vue.directive注册指令时使用
create(options: VuePluginDefaultConfigOption)创建 VuePlugin 插件使用

Example

1. main.js
import Vue from "vue";
import App from "./App.vue";

import { DeeplxTranslateEngine, TranslateVuePlugin } from "@spacechart/translate";

Vue.config.productionTip = false;
Vue.use(TranslateVuePlugin, {
    //翻译引擎
    engine: new DeeplxTranslateEngine({
        url: "/translate",
        authorization: "xx xx"
    }),
    //需要翻译的节点
    el: "#app"
});

new Vue({
    render: (h) => h(App)
}).$mount("#app");
2. App.vue
<template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png" />

        <HelloWorld msg="Welcome to Your Vue.js App" />
        <div class="div">
            你好 yes
            <div class="div" v-not-translate>How are you?</div>
        </div>
    </div>
</template>

<script>
    import HelloWorld from "./components/HelloWorld.vue";

    export default {
        name: "App",
        components: {
            HelloWorld
        },
        data() {
            return {};
        },
        mounted() {
            setTimeout(() => {
                this.$t.translate({
                    src: "EN",
                    target: "ZH",
                    languageMap: [
                        {
                            src: "EN",
                            target: "ZH",
                            srcText: "你好",
                            targetText: "Hello"
                        }
                    ]
                });
            });
        }
    };
</script>

HTML Plugin

HTML 插件通过TranslateHTMLPlugin类创建使用,支持not-translate属性排除需要翻译的文本(如下)

Options

属性类:HtmlPluginDefaultConfigOption

字段是否必填类型描述
engineITranslateEngine翻译引擎
elstring需要翻译的顶级节点

Methods

方法名描述
create(options: HtmlPluginDefaultConfigOption)创建 HtmlPlugin 插件使用

Example

index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="https://cdn.jsdelivr.net/npm/@spacechart/translate@1.0.1/dist/translate.min.js"></script>

    </head>
    <body>
        <div id="app">你好</div>
        <script>
            const { TranslateHTMLPlugin, DeeplxTranslateEngine } = translate;
            const plugin = TranslateHTMLPlugin.create({
                engine: new DeeplxTranslateEngine({
                    url: "/translate",
                    authorization: "xx xx"
                }),
                el: "#app"
            });

            plugin.translate({
                src: "ZH",
                target: "EN"
            });
        </script>
    </body>
</html>

FAQ

Vue 3.0 TypeError: Cannot read properties of undefined (reading '$t')

原因:在Vue 3.0 setup组合式函数中不能直接使用this对象来调用app.config.globalProperties配置的属性(在选项式中可以使用this直接访问)

解决方案:通过getCurrentInstance方法获取,如下

<script setup>
import { onMounted, getCurrentInstance } from "vue";

onMounted(() => {
      getCurrentInstance().proxy.$t.translate({
        src: "EN",
        target: "ZH"
    });
});
</script>

BUG Uncaught (in promise) TypeError: this._mapList.forEach is not a function

原因:在版本 v1.0.0 和 v1.0.1 中Deeplx引擎代码逻辑问题,导致默认值赋值错误

解决方案:省级版本至1.0.2及以上

Future

欢迎有共建想法的小伙伴加入到开源生态中

1.0.2

3 months ago

1.0.1

3 months ago

1.0.0

3 months ago