@vocab/react 1.1.19-update-chokidar-20251223005155 → 1.1.19

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