A module that parse object to pseudo HTML to translate and parse it back.
The core concept of this module is that google can translate any html while keeping its structure. Therefore, we can parse the pseudo HTML to translate and parse it back.
npm install google-object-translate
To use google-object-translate/translate
module, package @google-cloud/translate
is also required:
npm install @google-cloud/translate
import {translate} from 'google-object-translate';
const client = translate.ObjectTranslate.createClient('v2', {
// your google-cloud config here
// See: https://cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translateconfig
})
const objToTranslate = {
"title": "Hello World",
"viewerNumber": 1,
"content": "World",
"hybridList": [
"Hello",
null,
undefined,
"World"
]
}
const result = await client.translate(
objToTranslate,
// See: https://cloud.google.com/nodejs/docs/reference/translate/latest/translate/v2.translaterequest
{
from: 'en',
to: 'zh-CN',
})
// result = {
// "title": "你好世界",
// "viewerNumber": 1,
// "content": "世界",
// "hybridList": [
// "你好",
// null,
// undefined,
// "世界"
// ]
// }
import {parser} from 'google-object-translate';
- Arguments:
Name | Type | Required | Default | Comment |
---|---|---|---|---|
obj |
TranslationObject |
true | - | The object to translate |
filter |
(path: string[], sentence: Sentence) => boolean |
false | ()=>true | Filter function that decide a Sentence is translatable or not. True means it is translatable. |
- Return Type:
string
- Arguments:
Name | Type | Required | Default | Comment |
---|---|---|---|---|
pseudoHTML |
string |
true | - | - |
_originalObject | TranslationObject | false | undefined | The original object that will be merged to translated object. |
- Return Type:
TranslationObject
- Support v3 and v3-beta API in
translate.ts
Type | Alias for |
---|---|
Sentence | string | object | undefined |
SentenceArray | Sentence[] |
TranslationObject | Sentence | SentenceArray |
Some values will not be included to pseudo HTML because it's meaningless. This includes:
- Number
- Boolean
- Empty String
- null
- undefined
But these values in an array will be replaced with undefined
as placeholder.
before:
"some str"
after:
some str
Untranslatable item will become empty tag to maintain the structure.
before:
["item 1", 123, true, "item 2"]
after:
<body>
<ol>
<li>item 1</li>
<li></li>
<li></li>
<li>item 2</li>
</ol>
</body>
before:
{
"a": "",
"b": [
"item1",
2,
true
],
"c": null,
"d": {
"d1": "d1v",
"d2": "d2v"
}
}
after:
<body>
<div>
<ol id="b">
<li>item1</li>
<li></li>
<li></li>
</ol>
<div id="d">
<p id="d1">d1v</p>
<p id="d2">d2v</p>
</div>
</div>
</body>