This module provides utilities for handling locale-based translations.
It includes functions to retrieve values from nested objects using dot notation keys and to translate strings based on available locale files.
- Since:
- 2.0.0
- License:
- MIT
- Source:
Requires
- module:utils/type-utils
- module:error
- npm:@mitsuki31/deepget
Members
(inner, readonly) AVAILABLE_LOCALES :Array.<string>
The list of available locales.
Type:
- Array.<string>
- Since:
- 2.0.0
- Source:
(inner, readonly) LOCALES :Record.<string, (string|Array.<string>|object)>
The locales object containing all locale data.
Type:
- Record.<string, (string|Array.<string>|object)>
- Since:
- 2.0.0
- Source:
(inner) LOCALES_PATH :string
The path to the locales directory.
Type:
- string
- Since:
- 2.0.0
- Source:
(inner) SYSTEM_LOCALE :string
The system locale.
Type:
- string
- Since:
- 2.0.0
- Source:
Methods
(package, inner) translate(key, localesopt) → {string}
Retrieves a localized string for the given key based on the provided locale(s).
This function attempts to fetch the translation string from the LOCALES
object.
It follows a priority order where the first matching locale is used. If no match
is found, it falls back to system locale, default locale ('en'), or an empty string.
Fallback Rules
- If the provided locale is not available, it falls back to the system locale.
- If the translation for the system locale is not available, it falls back to the English translation.
Locale Priority
User-defined Locale >> System Locale >> Default Locale (English)
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
key |
string | The key path to retrieve the translation. |
|
locales |
string | Array.<string> |
<optional> |
The preferred locale(s) in order of priority. Can be a single string or an array of strings. Defaults to system locale if not specified. |
- Since:
- 2.0.0
- Source:
Throws:
-
If
locales
is neither a string nor an array of strings. - Type
- InvalidTypeError
Returns:
The translated string if found, or the system default locale, or the default English string, otherwise an empty string.
- Type
- string
Example
```json
// Assuming LOCALES contains:
{
en: { greeting: "Hello" },
fr: { greeting: "Bonjour" }
}
```
```js
translate('greeting', 'fr'); // "Bonjour"
translate('greeting', ['es', 'fr']); // "Bonjour" (fallback to 'fr')
translate('greeting', 'ja'); // "Hello" (fallback to system locale, assuming 'en')
```