0.3.2 • Published 1 year ago

@weareinreach/i18next-keys-ondemand v0.3.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

I18next with ability to download missing keys

Libraries.io dependency status for GitHub repo npm (scoped with tag)

Twitter Follow

Existing i18next backend plugins request keys by namespaces and not the granularity of an individual key. The goal of this module is to be able to fetch missing keys individually, taking in consideration performance by debouncing requests to an individual request.

Installation

# using pnpm
$ pnpm add @weareinreach/i18next-keys-ondemand

# using npm
$ npm install @weareinreach/i18next-keys-ondemand

# using yarn
$ yarn add @weareinreach/i18next-keys-ondemand

Usage

  • Use the module when initializing i18next:
import i18n from 'i18next'
import { I18nextKeysOnDemand, TranslationMap } from 'i18next-keys-ondemand'



const getterFunction = async (
        keys: string[], 
        language: string, 
        namespace: string, 
        defaultValues: Record<string,string>
    ) => {

    /** This function should ultimately return an object in the format of:
     *
     * {'key-name': 'Translated string value'}
     *
     */

    const result: Record<string,string> = await someFunctionThatHandlesThings(
        keys,
        language,
        namespace,
        defaultValues // pass defaultValues if you want to save new strings to your i18n store
        )

  return result
}

i18n
  .use(new I18nextKeysOnDemand({ translationGetter: getterFunction })) // init i18next here
  .init({
    fallbackLng: 'en',
    ns: ['yourNamespace'],
    defaultNS: 'yourNamespace',
    // saveMissing must be set to `true`!
    saveMissing: true,
  })
  • Options:
FieldMandatory?Default valueComment
translationGetteryesTranslation service function to use
missingKeyValueno''Value to return for missing keys
debounceDelayno100Delay in ms used to debounce the translation requests