Custom Translator
Terai is flexible regarding how you handle your translation process, allowing you to configure any translator of your choice.
A translator is simply a function that takes a dictionary and a language code and returns a translated dictionary.
Example
Consider the following terai.config.ts
file in your project:
import { defineConfig } from '@terai/dev'
export default defineConfig({
include: ['./src/**/*.{js,jsx,ts,tsx}'],
exclude: [],
projectLocale: 'en-US',
outLocales: ['es-ES', 'ja-JP'],
outDir: './locale',
})
This configuration indicates that you are using en-US
as your project locale and you want to generate translations for es-ES
and ja-JP
.
When you run terai extract
, it gathers all project messages and generates a dictionary in the locale directory with the following structure:
{
"dQxGBP": "Hello world!",
"eUqyLy": "Just focus on your messages and Terai will take of the rest!"
}
Now, let's add a custom translator to your configuration:
import { defineConfig } from '@terai/dev'
import type { Translator } from '@terai/dev'
const translator: Translator = async ({
dictionary, // Dictionary to be translated (en-US)
locale, // Destination locale (es-ES or ja-JP)
projectLocale, // en-US
}) => {
// Connect to any external service to translate your dictionaries
}
export default defineConfig({
include: ['./src/**/*.{js,jsx,ts,tsx}'],
exclude: [],
projectLocale: 'en-US',
outLocales: ['es-ES', 'ja-JP'],
outDir: './locale',
translator,
})
With this setup, every time you run terai extract
, Terai will call your custom translator function to translate the dictionary to the desired locales.
Ensure that the translator function returns a dictionary with the same keys as the original dictionary.
If everything goes well, you will find the translated dictionaries in the locale directory:
{
"dQxGBP": "¡Hola mundo!",
"eUqyLy": "¡Solo concéntrate en tus mensajes y Terai se encargará del resto!"
}
{
"dQxGBP": "こんにちは、世界!",
"eUqyLy": "メッセージに集中するだけで、Teraiが残りを引き受けます!"
}