@vocab/core 1.6.3 → 1.6.5-fix-messageformat-import-20250923004826

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/chunk-nOFOJqeH.js +30 -0
  2. package/dist/icu-handler-9mldObYa.js +29 -0
  3. package/dist/icu-handler-9mldObYa.js.map +1 -0
  4. package/dist/icu-handler-COUleaeZ.mjs +22 -0
  5. package/dist/icu-handler-COUleaeZ.mjs.map +1 -0
  6. package/dist/icu-handler.d.mts +7 -0
  7. package/dist/icu-handler.d.ts +7 -0
  8. package/dist/icu-handler.js +3 -0
  9. package/dist/icu-handler.mjs +3 -0
  10. package/dist/index.d.mts +53 -0
  11. package/dist/index.d.ts +53 -0
  12. package/dist/index.js +679 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/index.mjs +660 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/runtime.d.mts +8 -0
  17. package/dist/runtime.d.ts +8 -0
  18. package/dist/runtime.js +13 -0
  19. package/dist/runtime.js.map +1 -0
  20. package/dist/runtime.mjs +12 -0
  21. package/dist/runtime.mjs.map +1 -0
  22. package/dist/translation-file-BEIJ1-3N.js +34 -0
  23. package/dist/translation-file-BEIJ1-3N.js.map +1 -0
  24. package/dist/translation-file-CAOIsAU9.d.mts +7 -0
  25. package/dist/translation-file-DQOiWtfV.d.ts +7 -0
  26. package/dist/translation-file-Dn19n2oY.mjs +28 -0
  27. package/dist/translation-file-Dn19n2oY.mjs.map +1 -0
  28. package/dist/translation-file.d.mts +3 -0
  29. package/dist/translation-file.d.ts +3 -0
  30. package/dist/translation-file.js +3 -0
  31. package/dist/translation-file.mjs +3 -0
  32. package/dist/types-DFxEF4pq.d.mts +146 -0
  33. package/dist/types-Di9uIscO.d.ts +146 -0
  34. package/package.json +17 -28
  35. package/README.md +0 -724
  36. package/dist/declarations/src/compile.d.ts +0 -6
  37. package/dist/declarations/src/config.d.ts +0 -4
  38. package/dist/declarations/src/icu-handler.d.ts +0 -2
  39. package/dist/declarations/src/index.d.ts +0 -6
  40. package/dist/declarations/src/load-translations.d.ts +0 -32
  41. package/dist/declarations/src/runtime.d.ts +0 -3
  42. package/dist/declarations/src/translation-file.d.ts +0 -2
  43. package/dist/declarations/src/types.d.ts +0 -143
  44. package/dist/declarations/src/utils.d.ts +0 -26
  45. package/dist/declarations/src/validate/index.d.ts +0 -3
  46. package/dist/vocab-core.cjs.d.ts +0 -2
  47. package/dist/vocab-core.cjs.dev.js +0 -893
  48. package/dist/vocab-core.cjs.js +0 -7
  49. package/dist/vocab-core.cjs.prod.js +0 -893
  50. package/dist/vocab-core.esm.js +0 -866
  51. package/icu-handler/dist/vocab-core-icu-handler.cjs.d.ts +0 -2
  52. package/icu-handler/dist/vocab-core-icu-handler.cjs.dev.js +0 -31
  53. package/icu-handler/dist/vocab-core-icu-handler.cjs.js +0 -7
  54. package/icu-handler/dist/vocab-core-icu-handler.cjs.prod.js +0 -31
  55. package/icu-handler/dist/vocab-core-icu-handler.esm.js +0 -23
  56. package/icu-handler/package.json +0 -4
  57. package/runtime/dist/vocab-core-runtime.cjs.d.ts +0 -2
  58. package/runtime/dist/vocab-core-runtime.cjs.dev.js +0 -15
  59. package/runtime/dist/vocab-core-runtime.cjs.js +0 -7
  60. package/runtime/dist/vocab-core-runtime.cjs.prod.js +0 -15
  61. package/runtime/dist/vocab-core-runtime.esm.js +0 -10
  62. package/runtime/package.json +0 -4
  63. package/translation-file/dist/vocab-core-translation-file.cjs.d.ts +0 -2
  64. package/translation-file/dist/vocab-core-translation-file.cjs.dev.js +0 -35
  65. package/translation-file/dist/vocab-core-translation-file.cjs.js +0 -7
  66. package/translation-file/dist/vocab-core-translation-file.cjs.prod.js +0 -35
  67. package/translation-file/dist/vocab-core-translation-file.esm.js +0 -31
  68. package/translation-file/package.json +0 -4
package/README.md DELETED
@@ -1,724 +0,0 @@
1
- # Vocab
2
-
3
- Vocab is a strongly typed internationalization framework for React.
4
-
5
- Vocab helps you ship multiple languages without compromising the reliability of your site or slowing down delivery.
6
-
7
- - **Shareable translations**\
8
- Translations are co-located with the components that use them. Vocab uses the module graph allowing shared components to be installed with package managers like npm, just like any other module.
9
-
10
- - **Loading translations dynamically**\
11
- Vocab only loads the current user's language. If the language changes Vocab can load the new language behind the scenes without reloading the page.
12
-
13
- - **Strongly typed with TypeScript**\
14
- When using translations TypeScript will ensure code only accesses valid translations and translations are passed all required dynamic values.
15
-
16
- ## Getting started
17
-
18
- ### Step 1: Install Dependencies
19
-
20
- Vocab is a monorepo containing different packages you can install depending on your usage.
21
- The below list will get you started using the CLI and React integration.
22
-
23
- ```sh
24
- npm install --save-dev @vocab/cli
25
- npm install --save @vocab/core @vocab/react
26
- ```
27
-
28
- ### Step 2: Configure Vocab
29
-
30
- You can configure Vocab directly when calling the API, or via a `vocab.config.js` or `vocab.config.cjs` file.
31
-
32
- > [!TIP]
33
- > It's a good idea to name your languages using [IETF language tags], however this is not a requirement.
34
-
35
- In this example we've configured two languages named `en` (English) and `fr` (French).
36
- We've also configured a `devLanguage` of `en`.
37
- This is the language Vocab will assume when it sees a `translation.json` file without a language prefix.
38
-
39
- ```js
40
- // vocab.config.js
41
- module.exports = {
42
- languages: [{ name: 'en' }, { name: 'fr' }],
43
- devLanguage: 'en'
44
- };
45
- ```
46
-
47
- See the [configuration] section for more configuration options.
48
-
49
- [IETF language tags]: https://en.wikipedia.org/wiki/IETF_language_tag
50
- [configuration]: #configuration
51
-
52
- ### Step 3: Set the language using the React Provider
53
-
54
- Vocab uses React's context API to provide information for your translation lookups.
55
- To tell Vocab which language to use, wrap your app in a `VocabProvider` component and pass in a `language` prop corresponding to one of the language names configured in your `vocab.config.js` file.
56
-
57
- > [!NOTE]
58
- > Using methods discussed later we'll make sure the first language is loaded on page load.
59
- > However, after this, changing languages may lead to a period of no translations as Vocab downloads the new language's translations.
60
-
61
- ```tsx
62
- // src/App.tsx
63
-
64
- import { VocabProvider } from '@vocab/react';
65
-
66
- const App = ({ children }) => {
67
- return (
68
- <VocabProvider language="en">{children}</VocabProvider>
69
- );
70
- };
71
- ```
72
-
73
- If you need to customize the locale for your language, you can pass a `locale` prop to the `VocabProvider` component.
74
- This tells Vocab which locale to use when formatting your translations.
75
-
76
- ```tsx
77
- // src/App.tsx
78
-
79
- import { VocabProvider } from '@vocab/react';
80
-
81
- function App({ children }) {
82
- return (
83
- <VocabProvider language="myCustomLanguage" locale="en">
84
- {children}
85
- </VocabProvider>
86
- );
87
- }
88
- ```
89
-
90
- See [here][overriding the locale] for more information on how and when to use the `locale` prop.
91
-
92
- [overriding the locale]: #overriding-the-locale
93
-
94
- ### Step 4: Create translations
95
-
96
- A translation file is a JSON file consisting of a flat structure of keys.
97
- Each key must contain a `message` property, and optionally a `description` property.
98
-
99
- Rather than creating one giant file for each language's translations, Vocab enables you to co-locate the translations alongside their consuming components.
100
- To facilitate this, Vocab lets you group translations inside folders ending in `.vocab`.
101
- You may have as many of these folders as you like in your project.
102
-
103
- > [!TIP]
104
- > Your folders can be named anything, as long as it ends in `.vocab`.
105
- > It's recommened to just name your folders `.vocab` so you have one less name to think of/rename in the future.
106
-
107
- Translation files must follow the naming pattern of `{languageName}.translations.json`.
108
- The exception to this is translations for your `devLanguage` which must be placed in a file named `translations.json`.
109
-
110
- In the following examples, we're defining translations for our `devLanguage`, and a language named `fr`.
111
-
112
- ```jsonc
113
- // src/MyComponent/.vocab/translations.json
114
-
115
- {
116
- "my key": {
117
- "message": "Hello from Vocab",
118
- "description": "An optional description to help when translating"
119
- }
120
- }
121
- ```
122
-
123
- ```jsonc
124
- // src/MyComponent/.vocab/fr.translations.json
125
-
126
- {
127
- "my key": {
128
- "message": "Bonjour de Vocab",
129
- "description": "An optional description to help when translating"
130
- }
131
- }
132
- ```
133
-
134
- > [!NOTE]
135
- > You can create your translation files manually.
136
- > However, Vocab also offers integrations with remote translation platforms to push and pull translations automatically.
137
- > See [External translation tooling] for more information.
138
-
139
- [External translation tooling]: #external-translation-tooling
140
-
141
- ### Step 5: Compile and consume translations
142
-
143
- Once you have created some translations, run `vocab compile`.
144
- This command creates an `index.ts` file inside each folder ending in `.vocab`.
145
- Importing this file provides type-safe translations for your React components.
146
- Accessing translation messages is done by passing these imported translations to the `useTranslations` hook and using the returned `t` function.
147
-
148
- ```tsx
149
- // src/MyComponent.tsx
150
-
151
- import { useTranslations } from '@vocab/react';
152
- import translations from './.vocab';
153
-
154
- function MyComponent({ children }) {
155
- const { t } = useTranslations(translations);
156
-
157
- // t('my key') will return the appropriate translation based on the language set in your app's VocabProvider
158
- return <div>{t('my key')}</div>;
159
- }
160
- ```
161
-
162
- ### Step 6: [Optional] Set up Webpack plugin
163
-
164
- With the default setup, every language is loaded into your web application all the time, potentially leading to a large bundle size.
165
- Ideally you will want to switch out the Node.js/default runtime for the web runtime, which only loads the active language.
166
-
167
- This is done using the `VocabWebpackPlugin`.
168
- Applying this plugin to your client webpack configuration will replace all vocab files with dynamic asynchronous chunks designed for the web.
169
-
170
- ```sh
171
- npm i --save-dev @vocab/webpack
172
- ```
173
-
174
- ```js
175
- // webpack.config.js
176
-
177
- const { VocabWebpackPlugin } = require('@vocab/webpack');
178
-
179
- module.exports = {
180
- plugins: [new VocabWebpackPlugin()]
181
- };
182
- ```
183
-
184
- ### Step 7: [Optional] Optimize for fast page loading
185
-
186
- Using the above method without optimizing what chunks webpack uses you may find the page needing to do an extra round trip to load languages on a page.
187
-
188
- This is where `getChunkName` can be used to retrieve the Webpack chunk used for a specific language.
189
-
190
- For example, here is a server render function that would add the current language chunk to [Loadable component's ChunkExtractor](https://loadable-components.com/docs/api-loadable-server/#chunkextractor).
191
-
192
- ```tsx
193
- // src/render.tsx
194
-
195
- import { getChunkName } from '@vocab/webpack/chunk-name';
196
-
197
- // ...
198
-
199
- const chunkName = getChunkName(language);
200
-
201
- const extractor = new ChunkExtractor();
202
-
203
- extractor.addChunk(chunkName);
204
- ```
205
-
206
- ## Dynamic Values in Translations
207
-
208
- Translation messages can sometimes contain dynamic values, such as dates/times, links, usernames, etc.
209
- These values often exist somewhere in the middle of a message, and could change location depending on the translation.
210
- To support this, Vocab uses [Format.js's `intl-messageformat` library], which enables you to use [ICU Message syntax](https://formatjs.io/docs/core-concepts/icu-syntax/) in your messages.
211
-
212
- In the below example we are defining two messages: one that accepts a single parameter, and one that accepts a component.
213
-
214
- ```json
215
- {
216
- "my key with param": {
217
- "message": "Bonjour de {name}"
218
- },
219
- "my key with component": {
220
- "message": "Bonjour de <Link>Vocab</Link>"
221
- }
222
- }
223
- ```
224
-
225
- Vocab will automatically parse these strings as ICU messages and generate strict types for any parameters it finds.
226
-
227
- ```tsx
228
- t('my key with param', { name: 'Vocab' });
229
- t('my key with component', {
230
- Link: (children) => <a href="/foo">{children}</a>
231
- });
232
- ```
233
-
234
- [Format.js's `intl-messageformat` library]: https://formatjs.io/docs/intl-messageformat/
235
-
236
- ## Overriding the Locale
237
-
238
- By default, your language name is passed as the `locale` to the formatting API provided by [`intl-messageformat`].
239
- The `locale` is used to determine how to format dates, numbers, and other locale-sensitive values.
240
- If you wish to customize this behaviour, you can pass a `locale` prop to the `VocabProvider` component.
241
-
242
- ```tsx
243
- <VocabProvider language="myCustomLanguage" locale="th-TH">
244
- {children}
245
- </VocabProvider>
246
- ```
247
-
248
- This can be useful in certain situations:
249
-
250
- - You have chosen to name your language something other than an [IETF language tag], but still want to use a specific locale for formatting
251
- - You want to use a different locale for formatting a specific language.
252
- E.g. when formatting values for `th` (Thai) locales, the default calendar is Buddhist, but you may want to use the Gregorian calendar.
253
- This can be achieved by specifying a `locale` value with a BCP 47 extension sequence suffix such as `-u-ca-gregory`.
254
- For example: `th-u-ca-gregory`.
255
- See the [MDN Intl docs] for more information on BCP 47 extension sequences.
256
-
257
- [`intl-messageformat`]: https://formatjs.io/docs/intl-messageformat/
258
- [IETF language tag]: https://en.wikipedia.org/wiki/IETF_language_tag
259
- [mdn intl docs]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument
260
-
261
- ## Accessing the Current `language` or `locale`
262
-
263
- If you need to access either the `language` or `locale` that you passed to your `VocabProvider`, you can use the `useLanguage` hook:
264
-
265
- ```tsx
266
- import { useLanguage } from '@vocab/react';
267
-
268
- const MyComponent = () => {
269
- const { language, locale } = useLanguage();
270
- return (
271
- <div>
272
- {language} - {locale}
273
- </div>
274
- );
275
- };
276
- ```
277
-
278
- > [!CAUTION]\
279
- > `locale` is only available when you pass a `locale` prop to your `VocabProvider`.
280
- > If you don't pass a `locale` prop, `locale` will be `undefined`.
281
- > It's generally advised to name your languages using [IETF language tags] and let Vocab handle the locale for you.
282
- > This gives you the added benefit that you can use the `language` from `useLanguage` if necessary, and it will always be defined.
283
-
284
- Typically you won't need to access these values since the ICU message syntax supports locale-aware formatting of [numbers], [dates, and times].
285
- However, one use case where you might need to access these values is when formatting a currency value.
286
- This is because there is currently no way to specify the currency for an ICU message programmatically, so it must be hardcoded within the messsage.
287
- This poses a problem when you don't want to couple your translations to a specific currency.
288
-
289
- ```json
290
- {
291
- "my key with currency": {
292
- "message": "You have {value, number, ::compact-short currency/GBP}"
293
- }
294
- }
295
- ```
296
-
297
- When given a `value` of `123`, the above message would render as `You have GBP 123`.
298
-
299
- To format a value with a dynamic currency, you could use the `useLanguage` hook to access the current `language` and format the currency value using the `Intl.NumberFormat` API:
300
-
301
- ```tsx
302
- const Currency = ({ value, currency }) => {
303
- const { language } = useLanguage();
304
-
305
- const formattedValue = new Intl.NumberFormat(locale, {
306
- style: 'currency',
307
- currency
308
- }).format(value);
309
-
310
- return <div>{formattedValue}</div>;
311
- };
312
- ```
313
-
314
- [numbers]: https://formatjs.io/docs/core-concepts/icu-syntax/#number-type
315
- [dates, and times]: https://formatjs.io/docs/core-concepts/icu-syntax/#supported-datetime-skeleton
316
-
317
- ## Configuration
318
-
319
- Configuration can either be passed into the Node API directly or be gathered from the nearest `vocab.config.js` or `vocab.config.cjs` file.
320
-
321
- ```js
322
- // vocab.config.js
323
-
324
- function capitalize(element) {
325
- return element.toUpperCase();
326
- }
327
-
328
- function pad(message) {
329
- return '[' + message + ']';
330
- }
331
-
332
- module.exports = {
333
- devLanguage: 'en',
334
- languages: [
335
- { name: 'en' },
336
- { name: 'en-AU', extends: 'en' },
337
- { name: 'en-US', extends: 'en' },
338
- { name: 'fr-FR' }
339
- ],
340
- /**
341
- * An array of languages to generate based off translations for existing languages
342
- * Default: []
343
- */
344
- generatedLanguages: [
345
- {
346
- name: 'generatedLanguage',
347
- extends: 'en',
348
- generator: {
349
- transformElement: capitalize,
350
- transformMessage: pad
351
- }
352
- }
353
- ],
354
- /**
355
- * The root directory to compile and validate translations
356
- * Default: Current working directory
357
- */
358
- projectRoot: './example/',
359
- /**
360
- * A custom suffix to name vocab translation directories
361
- * Default: '.vocab'
362
- */
363
- translationsDirectorySuffix: '.vocab',
364
- /**
365
- * An array of glob paths to ignore from compilation and validation
366
- */
367
- ignore: ['**/ignored_directory/**']
368
- };
369
- ```
370
-
371
- ## Translation Key Types
372
-
373
- If you need to access the keys of your translations as a TypeScript type, you can use the `TranslationKeys` type from `@vocab/core`:
374
-
375
- ```jsonc
376
- // translations.json
377
- {
378
- "Hello": {
379
- "message": "Hello"
380
- },
381
- "Goodbye": {
382
- "message": "Goodbye"
383
- }
384
- }
385
- ```
386
-
387
- ```ts
388
- import type { TranslationKeys } from '@vocab/core';
389
- import translations from './.vocab';
390
-
391
- // "Hello" | "Goodbye"
392
- type MyTranslationKeys = TranslationKeys<
393
- typeof translations
394
- >;
395
- ```
396
-
397
- ## Generated languages
398
-
399
- Vocab supports the creation of generated languages via the `generatedLanguages` config.
400
-
401
- Generated languages are created by running a message `generator` over every translation message in an existing translation.
402
- A `generator` may contain a `transformElement` function, a `transformMessage` function, or both.
403
- Both of these functions accept a single string parameter and return a string.
404
-
405
- `transformElement` is applied to string literal values contained within `MessageFormatElement`s.
406
- A `MessageFormatElement` is an object representing a node in the AST of a compiled translation message.
407
- Simply put, any text that would end up being translated by a translator, i.e. anything that is not part of the [ICU Message syntax], will be passed to `transformElement`.
408
- An example of a use case for this function would be adding [diacritics] to every letter in order to stress your UI from a vertical line-height perspective.
409
-
410
- `transformMessage` receives the entire translation message _after_ `transformElement` has been applied to its individual elements.
411
- An example of a use case for this function would be adding padding text to the start/end of your messages in order to easily identify which text in your app has not been extracted into a `translations.json` file.
412
-
413
- By default, a generated language's messages will be based off the `devLanguage`'s messages, but this can be overridden by providing an `extends` value that references another language.
414
-
415
- ```js
416
- // vocab.config.js
417
-
418
- function capitalize(message) {
419
- return message.toUpperCase();
420
- }
421
-
422
- function pad(message) {
423
- return '[' + message + ']';
424
- }
425
-
426
- module.exports = {
427
- devLanguage: 'en',
428
- languages: [{ name: 'en' }, { name: 'fr' }],
429
- generatedLanguages: [
430
- {
431
- name: 'generatedLanguage',
432
- extends: 'en',
433
- generator: {
434
- transformElement: capitalize,
435
- transformMessage: pad
436
- }
437
- }
438
- ]
439
- };
440
- ```
441
-
442
- Generated languages are consumed the same way as regular languages.
443
- Any Vocab API that accepts a `language` parameter will work with a generated language as well as a regular language.
444
-
445
- ```tsx
446
- // App.tsx
447
-
448
- const App = () => (
449
- <VocabProvider language="generatedLanguage">
450
- <div>Hello, world!</div>
451
- </VocabProvider>
452
- );
453
- ```
454
-
455
- [icu message syntax]: https://formatjs.io/docs/intl-messageformat/#message-syntax
456
- [diacritics]: https://en.wikipedia.org/wiki/Diacritic
457
-
458
- ## Pseudo-localization
459
-
460
- The `@vocab/pseudo-localize` package exports low-level functions that can be used for pseudo-localization of translation messages.
461
-
462
- ```sh
463
- $ npm install --save-dev @vocab/pseudo-localize
464
- ```
465
-
466
- ```ts
467
- import {
468
- extendVowels,
469
- padString,
470
- pseudoLocalize,
471
- substituteCharacters
472
- } from '@vocab/pseudo-localize';
473
-
474
- const message = 'Hello';
475
-
476
- // [Hello]
477
- const paddedMessage = padString(message);
478
-
479
- // Ḩẽƚƚö
480
- const substitutedMessage = substituteCharacters(message);
481
-
482
- // Heelloo
483
- const extendedMessage = extendVowels(message);
484
-
485
- // Extend the message and then substitute characters
486
- // Ḩẽẽƚƚöö
487
- const pseudoLocalizedMessage = pseudoLocalize(message);
488
- ```
489
-
490
- Pseudo-localization is a transformation that can be applied to a translation message.
491
- Vocab's implementation of this transformation contains the following elements:
492
-
493
- - _Start and end markers (`padString`):_ All strings are encapsulated in `[` and `]`.
494
-
495
- If a developer doesn’t see these characters they know the string has been clipped by an inflexible UI element.
496
-
497
- - _Transformation of ASCII characters to extended character equivalents (`substituteCharacters`):_ Stresses the UI from a vertical line-height perspective, tests font and encoding support, and weeds out strings that haven’t been externalized correctly (they will not have the pseudo-localization applied to them).
498
-
499
- - _Padding text (`extendVowels`):_ Simulates translation-induced expansion.
500
-
501
- Vocab's implementation of this involves repeating vowels (and `y`) to simulate a 40% expansion in the message's length.
502
-
503
- This [Netflix technology blog post] inspired Vocab's implementation of this functionality.
504
-
505
- [netflix technology blog post]: https://netflixtechblog.com/pseudo-localization-netflix-12fff76fbcbe
506
-
507
- ### Generating a pseudo-localized language using Vocab
508
-
509
- Vocab can generate a pseudo-localized language via the [`generatedLanguages` config][generated languages config], either via the webpack plugin or your `vocab.config.js` or `vocab.config.cjs` file.
510
- `@vocab/pseudo-localize` exports a `generator` that can be used directly in your config.
511
-
512
- ```js
513
- // vocab.config.js
514
-
515
- const { generator } = require('@vocab/pseudo-localize');
516
-
517
- module.exports = {
518
- devLanguage: 'en',
519
- languages: [{ name: 'en' }, { name: 'fr' }],
520
- generatedLanguages: [
521
- {
522
- name: 'pseudo',
523
- extends: 'en',
524
- generator
525
- }
526
- ]
527
- };
528
- ```
529
-
530
- [generated languages config]: #generated-languages
531
-
532
- ## Use Without React
533
-
534
- If you need to use Vocab outside of React, you can access the translations directly.
535
- You'll then be responsible for when to load translations and how to update on translation load.
536
-
537
- #### Async access
538
-
539
- - `getMessages(language: string) => Promise<Messages>` returns messages for the given language formatted according to the correct locale.
540
- If the language has not been loaded it will load the language before resolving.
541
-
542
- > [!NOTE]
543
- > To optimize loading time you may want to call [`load`] ahead of use.
544
-
545
- [`load`]: #sync-access
546
-
547
- #### Sync access
548
-
549
- - `load(language: string) => Promise<void>` attempts to pre-load messages for the given language, resolving once loaded.
550
- This function only ensures the language is available and does not return any translations.
551
- - `getLoadedMessages(language: string) => Messages | null` returns messages for the given language formatted according to the correct locale.
552
- If the language has not been loaded it will return `null`.
553
- This will not load a language that is not available.
554
- Useful when a synchronous (non-promise) return is required.
555
-
556
- **Example: Promise based formatting of messages**
557
-
558
- ```ts
559
- import translations from './.vocab';
560
-
561
- async function getFooMessage(language) {
562
- let messages = await translations.getMessages(language);
563
- return messages['my key'].format();
564
- }
565
-
566
- getFooMessage().then((m) => console.log(m));
567
- ```
568
-
569
- **Example: Synchronously returning a message**
570
-
571
- ```ts
572
- import translations from './.vocab';
573
-
574
- function getFooMessageSync(language) {
575
- let messages = translations.getLoadedMessages(language);
576
- if (!messages) {
577
- // Translations not loaded, start loading and return null for now
578
- translations.load();
579
- return null;
580
- }
581
- return messages.foo.format();
582
- }
583
-
584
- translations.load();
585
-
586
- const onClick = () => {
587
- console.log(getFooMessageSync());
588
- };
589
- ```
590
-
591
- ## Generate Types
592
-
593
- Vocab generates custom `index.ts` files that give your React components strongly typed translations to work with.
594
-
595
- To generate these files run:
596
-
597
- ```sh
598
- vocab compile
599
- ```
600
-
601
- Or to re-run the compiler when files change:
602
-
603
- ```sh
604
- vocab compile --watch
605
- ```
606
-
607
- ## External Translation Tooling
608
-
609
- Vocab can be used to synchronize your translations with translations from a remote translation platform.
610
-
611
- | Platform | Environment Variables |
612
- | -------- | ----------------------------------- |
613
- | [Phrase] | PHRASE_PROJECT_ID, PHRASE_API_TOKEN |
614
-
615
- ```sh
616
- vocab push --branch my-branch
617
- vocab pull --branch my-branch
618
- ```
619
-
620
- ### [Phrase] Platform Features
621
-
622
- #### Delete Unused keys
623
-
624
- When uploading translations, Phrase identifies keys that exist in the Phrase project, but were not
625
- referenced in the upload. These keys can be deleted from Phrase by providing the
626
- `--delete-unused-keys` flag to `vocab push`. E.g.
627
-
628
- ```sh
629
- vocab push --branch my-branch --delete-unused-keys
630
- ```
631
-
632
- [phrase]: https://developers.phrase.com/api/
633
-
634
- #### [Tags]
635
-
636
- `vocab push` supports uploading [tags] to Phrase.
637
-
638
- Tags can be added to an individual key via the `tags` property:
639
-
640
- ```jsonc
641
- // translations.json
642
-
643
- {
644
- "Hello": {
645
- "message": "Hello",
646
- "tags": ["greeting", "home_page"]
647
- },
648
- "Goodbye": {
649
- "message": "Goodbye",
650
- "tags": ["home_page"]
651
- }
652
- }
653
- ```
654
-
655
- Tags can also be added under a top-level `_meta` field. This will result in the tags applying to all
656
- keys specified in the file:
657
-
658
- ```jsonc
659
- // translations.json
660
-
661
- {
662
- "_meta": {
663
- "tags": ["home_page"]
664
- },
665
- "Hello": {
666
- "message": "Hello",
667
- "tags": ["greeting"]
668
- },
669
- "Goodbye": {
670
- "message": "Goodbye"
671
- }
672
- }
673
- ```
674
-
675
- In the above example, both the `Hello` and `Goodbye` keys would have the `home_page` tag attached to
676
- them, but only the `Hello` key would have the `usage_greeting` tag attached to it.
677
-
678
- > [!NOTE]
679
- > Only tags specified on keys in your [`devLanguage`][configuration] will be uploaded.
680
- > Tags on keys in other languages will be ignored.
681
-
682
- [tags]: https://support.phrase.com/hc/en-us/articles/5822598372252-Tags-Strings-
683
- [configuration]: #configuration
684
-
685
- #### Global key
686
-
687
- `vocab push` and `vocab pull` can support global keys mapping. When you want certain translations to use a specific/custom key in Phrase, add the `globalKey` to the structure.
688
-
689
- ```jsonc
690
- // translations.json
691
-
692
- {
693
- "Hello": {
694
- "message": "Hello",
695
- "globalKey": "hello"
696
- },
697
- "Goodbye": {
698
- "message": "Goodbye",
699
- "globalKey": "app.goodbye.label"
700
- }
701
- }
702
- ```
703
-
704
- In the above example,
705
-
706
- - `vocab push` will push the `hello` and `app.goodbye.label` keys to Phrase.
707
- - `vocab pull` will pull translations from Phrase and map them to the `hello` and `app.goodbye.label` keys.
708
-
709
- ##### Error on no translation for global key
710
-
711
- By default, `vocab pull` will not error if a translation is missing in Phrase for a translation with a global key.
712
- If you want to throw an error in this situation, pass the `--error-on-no-global-key-translation` flag:
713
-
714
- ```sh
715
- vocab pull --error-on-no-global-key-translation
716
- ```
717
-
718
- ## Troubleshooting
719
-
720
- ### Problem: Passed locale is being ignored or using en-US instead
721
-
722
- When running in Node.js, the locale formatting is supported by [Node.js's Internationalization support](https://nodejs.org/api/intl.html#intl_internationalization_support).
723
- Node.js will silently switch to the closest locale it can find if the passed locale is not available.
724
- See Node's documentation on [Options for building Node.js](https://nodejs.org/api/intl.html#intl_options_for_building_node_js) for information on ensuring Node has the locales you need.