https://github.com/zakkudo/translator
Helper class to make working with translations enjoyable.
https://github.com/zakkudo/translator
Last synced: 3 months ago
JSON representation
Helper class to make working with translations enjoyable.
- Host: GitHub
- URL: https://github.com/zakkudo/translator
- Owner: zakkudo
- License: mit
- Created: 2018-08-04T13:52:46.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-07T04:14:42.000Z (over 2 years ago)
- Last Synced: 2025-03-08T10:38:30.915Z (3 months ago)
- Language: TypeScript
- Homepage:
- Size: 1.12 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
- [README](#readme)
- [@zakkudo/translator](#zakkudotranslator)
- [Why use this?](#why-use-this)
- [Install](#install)
- [Message JSON Format](#message-json-format)
- [Usage](#usage)
- [Example Project](#example-project)
- [Interpolation](#interpolation)
- [Formatting Date, Time, and Currency.](#formatting-date-time-and-currency)
- [Also See](#also-see)
- [Classes](#classes)
- [Default](#default)
- [Class: default](#class-default)
- [Modules](#modules)
- [@zakkudo/translator](#zakkudotranslator-1)
- [Table of contents](#table-of-contents)# README
## @zakkudo/translator
Helper class to make working with translations enjoyable.
[](https://travis-ci.org/zakkudo/translator)
[](https://coveralls.io/github/zakkudo/translator?branch=master)
[](https://snyk.io/test/github/zakkudo/translator)
[](https://nodejs.org/)
[](https://opensource.org/licenses/MIT)### Why use this?
- Make development easier and faster with human readable text in code. Not variables.
- Ease maintenance by automatically generating your localization strings.
- Give your localization team access to easy to use localization tools like [POEdit](https://poedit.net/)
- Automatically only pass in the translation strings your app is using to make it fast!
- Use [@zakkudo/translation-static-analyzer](https://www.npmjs.com/package/@zakkudo/translation-static-analyzer) or [@zakkudo/translate-webpack-plugin](https://www.npmjs.com/package/@zakkudo/translate-webpack-plugin) to automatically generate your translation files
- You should prefer [@zakkudo/translator-react](https://www.npmjs.com/package/@zakkudo/translator-react) for react projects.### Install
```console
## Install using npm
npm install @zakkudo/translator
``````console
## Install using yarn
yarn add @zakkudo/translator
```### Message JSON Format
The localization format is meant to decrease the size of the json files and
make it easy to mainten them. Many gettext javascript extractors will generate
a format similar to this one.Explicitly supplying context is optional. The context defaults to a blank string
when not explicitly declared.```javascript
const localization = {
// Your configuratoin for plural handling. Often this will be generated by your localization software.
"": "Plural-Forms: nplurals=2; plural=n > 1;",// Singular localization
"I like to walk to the store.": "J'aime marcher jusqu"au magasin.",// Singular localizations with context
"wind": {
"noun": "vent"
"verb": "remontre"
}
},// Plural localization
"You have %d item in your cart.:You have %d items in your cart.": [
"Vous avez %d article dans votre panier",
"Vous avez %d articles dans votre panier",
],
};
```\*Note: `'\'` and `':'` in the localizations should be escaped in the dictionary. If you use a tool to generate the localizatoin,
you won't have to worry about this.- `'\' -> '\\u{5C}'`
- `':' -> '\\u{3A}'`### Usage
If you were to use the above localization, it would look similar to this:
```javascript
// Create a translation store instance and make it default to the french localization
const translation = new Translation("fr-FR");// Add the localization dictionary as declaired above.
translation.setLocalization("fr-FR", localization);// Alias the gettext calls to something more convenient.
const { gettext: __, gettext: __n, gettext: __p } = translation;// output: "J"aime marcher jusqu"au magasin."
console.log(__("I like to walk to the store."));// output: "Vous avez 2 articles dans votre panier"
console.log(
__n("You have %d item in your cart.", "You have %d items in your cart.", 2)
);// output: "vent"
console.log(__p("noun", "wind"));
```### Example Project
Look at this example project
### Interpolation
This internationalization library supports all standard gettext/printf interpolations. The below is a table of your
primary options:| Parameter | Meaning |
| :-------- | :------------------------------------------------------------------------------------------- |
| %b | Print a boolean |
| %B | Print a boolean in capital letters |
| %d | Print an integer number printed in decimal |
| %f | Print a floating point number ( in the form dddd.dddddd). |
| %e | Print a floating point number ( in scientific notation: d.dddEddd). |
| %E | Print a floating point number ( in scientific notation: d.dddEddd). |
| %x | Print an integer number in hexadecimal with lower case letters. |
| %X | Print an integer number printed in hexadecimal with upper case letters. |
| %c | Print a character. |
| %C | Print a character in uppercase. |
| %s | Print a string. |
| %S | Print a string in uppercase. |
| %r | Preserve an object by splitting string into an array and inserting the object in the middle. |`%r` is not printf standard parameter. It is designed to better let this library integrate into different UI toolkits. As
an example, this parameter can be used as a base for a helper that generates react components.### Formatting Date, Time, and Currency.
When needing to format dates, time or currency, it recommended you use the native Intl library. This functionality may be internalized in the future usign a thin wrapper.
- [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) Use this method for writing `5 minutes ago` style strings.
- [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) Use this method for date and time formatting.
- [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) Use this method for currency formatting.#### Interpolation Examples
This library wraps a printf implementation, which means most interpolations shoudl work and are controllable by the translators.
```javascript
// %c character
translation.gettext("%c", "b");
// => 'c'// %C converts to uppercase character (if not already)
translation.gettext("%C", "b");
// => 'B'// %d decimal integer (base 10)
translation.gettext("%d", 100);
// => '100'// %0Xd zero-fill for X digits
translation.gettext("%05d", 1);
// => '00001'// %Xd right justify for X digits
translation.gettext("%5d", 1);
// => ' 1'// %-Xd left justify for X digits
translation.gettext("%-5d", 1);
// => '1 '// %+d adds plus sign(+) to positive integers, minus sign for negative integers(-)
translation.gettext("%+5d", 1);
// => ' +1'
translation.gettext("%+5d", -1);
// => ' -1'// %e scientific notation
translation.gettext("%e", 52.8);
// => '5.28e+1'// %E scientific notation with a capital 'E'
translation.gettext("%E", 52.8);
// => '5.28E+1'// %f floating-point number
translation.gettext("%f", 52.8);
// => '52.8'// %.Yf prints Y positions after decimal
translation.gettext("%.1f", 1.234);
// => '1.2'// %Xf takes up X spaces
translation.gettext("%5f", 123);
// => ' 123'// %0X.Yf zero-fills
translation.gettext("%05.1f", 1.234);
// => '001.2'// %-X.Yf left justifies
translation.gettext("%-5.1f", 1.234);
// => '1.2 '// %i integer (base 10)
translation.gettext("%i", 123);
// => '123'// %b converts to boolean
translation.gettext("%b", true);
// => 'true'
translation.gettext("%b", "true");
// => 'true'
translation.gettext("%b", 1);
// => 'true'// %B converts to uppercase boolean
translation.gettext("%b", true);
// => 'TRUE'
translation.gettext("%b", "true");
// => 'TRUE'
translation.gettext("%b", 1);
// => 'TRUE'// %o octal number (base 8)
translation.gettext("%o", 8);
// => '10'// %s a string of characters
translation.gettext("%s", "foo");
// => 'foo'// %Xs formats string for a minimum of X spaces
translation.gettext("%5s", "foo");
// => ' foo'// %-Xs left justify
translation.gettext("%-5s", "foo");
// => 'foo '// %S converts to a string of uppercase characters (if not already)
translation.gettext("%S", "foo");
// => 'FOO'// %u unsigned decimal integer
translation.gettext("%u", 1);
// => '1'
translation.gettext("%u", -1);
// => '4294967295'// %x number in hexadecimal (base 16)
translation.gettext("%x", 255);
// => 'ff'// %% prints a percent sign
translation.gettext("%%");
// => '%'// \% prints a percent sign
translation.gettext("\\%");
// => '%'// %2$s %1$s positional arguments
translation.gettext("%2$s %1$s", "bar", "foo");
// => 'foo bar'// Break the string into an array, where the elements are preserved. This is very useful for integration of this library into differnt ui toolkits.
translation.gettext("You have %r tickets", );
// => 'foo bar'
```### Also See
- [fast-printf](https://www.npmjs.com/package/fast-printf)
- [gettext](https://www.gnu.org/software/gettext/manual/gettext.html)
- [@zakkudo/translator-react](https://github.com/zakkudo/translator-react)# Classes
## Default
[@zakkudo/translator](#readme) / [Exports](#modules) / default
### Class: default
#### Table of contents
##### Constructors
- [constructor](#constructor)
##### Properties
- [locale](#locale)
- [localizations](#localizations)##### Methods
- [gettext](#gettext)
- [mergeLocalization](#mergelocalization)
- [ngettext](#ngettext)
- [npgettext](#npgettext)
- [pgettext](#pgettext)
- [setLocalization](#setlocalization)#### Constructors
##### constructor
• **new default**(`locale?`)
###### Parameters
| Name | Type |
| :------- | :------- |
| `locale` | `string` |###### Defined in
[index.ts:257](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L257)
#### Properties
##### locale
• **locale**: `string`
The currently set locale. Defaults to a blank string which represents the fallback locale.
###### Defined in
[index.ts:255](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L255)
---
##### localizations
• **localizations**: `Object` = `{}`
The localization store.
###### Index signature
▪ [key: `string`]: `Localization`
###### Defined in
[index.ts:252](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L252)
#### Methods
##### gettext
▸ **gettext**(`key`, ...`leftover`): `string` \| `unknown`[]
Get the mapping for a specific string using the currently set locale. If the mapping does
not exist, the value is passed through.###### Parameters
| Name | Type | Description |
| :------------ | :---------- | :--------------------------------------------------------------------- |
| `key` | `string` | - |
| `...leftover` | `unknown`[] | Leftover arguments to use for interpolation where `%d` or `%s` is used |###### Returns
`string` \| `unknown`[]
The localized string if it exists, otherwise the text is passed through as a fallback
###### Defined in
[index.ts:341](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L341)
---
##### mergeLocalization
▸ **mergeLocalization**(`locale`, `localization`): `void`
Incrementally merges a localization into an existing one.
###### Parameters
| Name | Type | Description |
| :------------- | :----------------------- | :---------------------------------------- |
| `locale` | `string` | The locale to merge into |
| `localization` | `CompressedLocalization` | The data to merge with the existing data. |###### Returns
`void`
###### Defined in
[index.ts:316](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L316)
---
##### ngettext
▸ **ngettext**(`singular`, `plural`, `count`, ...`leftover`): `string` \| `unknown`[]
Translates a plural string.
###### Parameters
| Name | Type | Description |
| :------------ | :---------- | :----------------------------------------------------- |
| `singular` | `string` | The singular version of the string, such as `%s apple` |
| `plural` | `string` | The plural version of the string, such as `%s apples` |
| `count` | `number` | Count used to determine which version is used |
| `...leftover` | `unknown`[] | - |###### Returns
`string` \| `unknown`[]
The localized string if it exists, otherwise the text is passed through as a fallback
###### Defined in
[index.ts:356](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L356)
---
##### npgettext
▸ **npgettext**(`context`, `singular`, `plural`, `count`, ...`leftover`): `string` \| `unknown`[]
Translates a particular version of a plural string denoted by the context.
###### Parameters
| Name | Type | Description |
| :------------ | :---------- | :--------------------------------------------------------------------------------------------------------------------- |
| `context` | `string` | The translation context, used for diambiguating usages of a word that would map to different words in another language |
| `singular` | `string` | The singular version of the string, such as `%s apple` |
| `plural` | `string` | The plural version of the string, such as `%s apples` |
| `count` | `number` | Count used to determine which version is used |
| `...leftover` | `unknown`[] | - |###### Returns
`string` \| `unknown`[]
The localized string if it exists, otherwise the text is passed through as a fallback
###### Defined in
[index.ts:402](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L402)
---
##### pgettext
▸ **pgettext**(`context`, `key`, ...`leftover`): `string` \| `unknown`[]
Get the mapping for a specific string using the currently set locale. If the mapping does
not exist, the value is passed through.###### Parameters
| Name | Type | Description |
| :------------ | :---------- | :--------------------------------------------------------------------------------------------------------------------- |
| `context` | `string` | The translation context, used for diambiguating usages of a word that would map to different words in another language |
| `key` | `string` | - |
| `...leftover` | `unknown`[] | Leftover arguments to use for interpolation where `%d` or `%s` is used |###### Returns
`string` \| `unknown`[]
The localized string if it exists, otherwise the text is passed through as a fallback
###### Defined in
[index.ts:381](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L381)
---
##### setLocalization
▸ **setLocalization**(`locale`, `localization`): `void`
Overwrites a specific localization with a new one.
###### Parameters
| Name | Type | Description |
| :------------- | :----------------------- | :--------------------------- |
| `locale` | `string` | The locale to overwrite |
| `localization` | `CompressedLocalization` | The new localization mapping |###### Returns
`void`
###### Defined in
[index.ts:305](https://github.com/zakkudo/translator/blob/b42a398/src/index.ts#L305)
# Modules
[@zakkudo/translator](#readme) / Exports
## @zakkudo/translator
### Table of contents
#### Classes
- [default](#default)