Translator

Customisable translator for backend and frontend usage with a statically typed translations facade.

Source code is hosted on GitHub

  • Works for server side and client side translations handling

  • Features static translations access, without using string based keys

  • Extremely easy to use and customise

  • Not bloated with unnecessary features

yarn add @corets/translator

Seamless React integration is shipped in a separate package:

useTranslator

Static translation access

Translations can be accessed in a static manner thanks to the createTranslatorAccessor() helper. Check out @corets/use-translator docs for an example usage in React.

Custom interpolations

Provide a custom interpolation function used for replacement of placeholders with values:

import { createTranslator } from "@corets/translator"

const customInterpolator = (text: string, match: string, replacement: any) => {  
    return text.replace(`[[${match}]]`, replacement)
}
const translator = createTranslator({}, { interpolator: customInterpolator })

You can access the default interpolation function anytime:

import { translatorInterpolator } from "@corets/translator"

Custom formatting

Provide a custom formatter function used to format replacements before interpolation:

import { createTranslator, translatorFormatter } from "@corets/translator"
import dayjs from "dayjs"

const customFormatter = (language: string, replacement: any, replacements: object) => {  
    if (replacement instanceof Date) {    
        const format = replacements?.format ?? "DD.MM.YYYY"    
        
        return dayjs(replacement).format(format)  
    }  
    
    return defaultTranslatorFormatter(language, replacement, replacements)
} 

const translator = createTranslator({}, { formatter: customFormatter })

Custom placeholders

Provide a custom placeholder function used to generate placeholders for missing translation keys:

import { createTranslator } from "@corets/translator"

const customPlaceholder = (language: string, key: string, replacements: object) => `${language}.${key}`

const translator = createTranslator({}, { placeholder: customPlaceholder })

You can access the default placeholder function anytime:

import { translatorPlaceholder } from "@corets/translator"

createTranslator()

Create a new Translator instance:

import { createTranslator } from "@corets/translator"

const translations = {  
    en: { title: "Welcome" },  
    de: { title: "Willkommen" }
}

const translator = createTranslator(translations, { language: "en" })

Create a translator instance without the factory function:

import { Translator } from "@corets/translator"

const translator = new Translator({}, { language: "en" })

createTranslatorAccessor()

Create a statically typed facade for your translations. This allows you to access translations in a statically typed manner, no need to use string based translation keys anymore. Trying to access missing translations will lead to a compilation error! 💥

import { createTranslator, createTranslatorAccessor } from "@corets/translator"

const translations = {  
    en: { some: { nested: "value", another: "Hello {greeting}"} },  
    de: { some: { nested: "other"} },
}

const translator = createTranslator(translations, { language: "en" })
const locales = createTranslatorAccessor(translator, translations.en)

locales.some.nested.get()
locales.some.another.get({ replace: { greeting: "World" } })
locales.some.nested.get({ language: "de" })

This functionality is powered by the accessor library:

Accessor

Translator.config()

Configure translator:

import { createTranslator } from "@corets/translator"

const translator = createTranslator({ ... }, { language: "en" })

translator.config({  
    language: "en",  
    fallbackLanguage: "de",  
    interpolate: true,  
    formatter,  
    interpolator,  
    placeholder,
})

Translator.getLanguage()

Get current language:

translator.getLanguage()

Translator.setLanguage()

Change current language:

translator.setLanguage("en")

Translator.getLanguages()

Get all registered languages:

translator.getLanguages()

Translator.getFallbackLanguage()

Get fallback language:

transaltor.getFallbackLanguage()

A fallback language is used whenever a translation key is missing for current language.

Translator.setFallbackLanguage()

Change fallback language:

translator.setFallbackLanguage("de")

Translator.getTranslations()

Get all registered translations:

translator.getTranslations()

Returned object looks something like this:

{  
    en: { key: "value" },  
    de: { key: "value" },
}

Translator.getTranslationsForLanguage()

Get all translations for a specific language:

translator.getTranslationsForLanguage("en")

The returned object looks something like this:

{ key: "value" }

Translator.setTranslations()

Replace all translations, for all languages, with the new ones:

translator.setTranslations({ en: { key: "value" }})

Translator.setTranslationsForLanguage()

Replace all translations for a specific language:

translator.setTranslationsForLanguage("en", { key: "value" })

Translator.addTranslations()

Update all translations, in all languages, using a merge:

translator.addTranslations({ de: { key: "value" } })

Contrary to the Translator.setTranslations() method, this one will not replace all translations but do a merge instead.

Translator.addTranslationsForLanguage()

Add translations, for a specific language, using a merge:

translator.addTranslationsForLanguage("en", { key: "value" })

Contrary to the Translator.setTranslationsForLanguage() method, this one will not replace all translations but do a merge instead.

Translator.get()

Retrieve a translation:

translator.get("key")

Retrieve a translation with a nested key:

translator.get("nested.key")

Retrieve translation for another language:

translator.get("key", { language: "de" })

Retrieve translation with another fallback language:

translator.get("key", { fallbackLanguage: "de" })

Retrieve translation without interpolating it:

translator.get("key", { interpolate: false })

Retrieve a translation and interpolate some values, using array syntax:

// given translation: {{1}} and {{2}} are colors
translator.get("key", ["red", "blue"])

Retrieve a translation and interpolate some values, using object syntax:

// given translations: {{color1}} and {{color2}} are colors
translator.get("key", { color1: "red", color2: "blue" })

Retrieve translation with a custom formatter, interpolator and placeholder:

translator.get("key", { formatter, interpolator, placeholder })

Check out documentation for formatter, interpolator, and placeholder.

Translator.has()

Check if translation exists:

translator.has("key")

Check if translation exists for a specific language:

translator.has("key", { language: "en" })

Check if translation exists in the current language or in a specific fallback language:

translator.has("key", { fallbackLanguage: "de" })

Translator.t()

Create a standalone translation function:

const t = translator.t()

t("key")

// same as
translator.get("key")

Create a translation function for a specific scope:

const t = translator.t("nested.scope")

t("key")

// same as
translator.get("nested.scope.key")

Override scope with ~:

const t = translator.t("nested.key")

t("~key")

// same as
translator.get("key")

This method supports the same options object as Translator.get().

Translator.listen()

Listen to any kind of changes, like language change, translations change, etc.:

const unsubscribe = translator.listen(() => console.log("something has changed"))

unsubscribe()

Last updated