{"id":13727002,"url":"https://github.com/seek-oss/vocab","last_synced_at":"2026-04-02T11:37:21.588Z","repository":{"id":36991747,"uuid":"314113328","full_name":"seek-oss/vocab","owner":"seek-oss","description":"Vocab is a strongly typed internationalization framework for React","archived":false,"fork":false,"pushed_at":"2025-04-27T17:38:10.000Z","size":2147,"stargazers_count":130,"open_issues_count":4,"forks_count":7,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-30T04:39:47.752Z","etag":null,"topics":["i18n","internationalization","language","react","translation","typescript","webpack"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/seek-oss.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-11-19T02:21:41.000Z","updated_at":"2025-04-22T06:38:10.000Z","dependencies_parsed_at":"2023-10-20T16:02:36.896Z","dependency_job_id":"658e4a7a-b974-4833-a7cd-e4af73d28471","html_url":"https://github.com/seek-oss/vocab","commit_stats":{"total_commits":294,"total_committers":16,"mean_commits":18.375,"dds":0.7380952380952381,"last_synced_commit":"dad4649d2898c3ba7277598af343aac0581f7ccc"},"previous_names":[],"tags_count":204,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seek-oss%2Fvocab","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seek-oss%2Fvocab/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seek-oss%2Fvocab/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seek-oss%2Fvocab/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/seek-oss","download_url":"https://codeload.github.com/seek-oss/vocab/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252965146,"owners_count":21832828,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["i18n","internationalization","language","react","translation","typescript","webpack"],"created_at":"2024-08-03T01:03:35.186Z","updated_at":"2026-01-19T07:12:35.415Z","avatar_url":"https://github.com/seek-oss.png","language":"TypeScript","funding_links":[],"categories":["webpack","TypeScript"],"sub_categories":[],"readme":"# Vocab\n\nVocab is a strongly typed internationalization framework for React.\n\nVocab helps you ship multiple languages without compromising the reliability of your site or slowing down delivery.\n\n- **Shareable translations**\\\n  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.\n\n- **Loading translations dynamically**\\\n  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.\n\n- **Strongly typed with TypeScript**\\\n  When using translations TypeScript will ensure code only accesses valid translations and translations are passed all required dynamic values.\n\n## Table of contents\n\n- [Getting started](#getting-started)\n  - [Step 1: Install Dependencies](#step-1-install-dependencies)\n  - [Step 2: Configure Vocab](#step-2-configure-vocab)\n  - [Step 3: Set the language using the React Provider](#step-3-set-the-language-using-the-react-provider)\n  - [Step 4: Create translations](#step-4-create-translations)\n  - [Step 5: Compile and consume translations](#step-5-compile-and-consume-translations)\n  - [Step 6: [Optional] Set up plugin](#step-6-optional-set-up-plugin)\n  - [Step 7: [Optional] Optimize for fast page loading](#step-7-optional-optimize-for-fast-page-loading)\n\n## Getting started\n\n### Step 1: Install Dependencies\n\nVocab is a monorepo containing different packages you can install depending on your usage.\nThe below list will get you started using the CLI and React integration.\n\n```sh\nnpm install --save-dev @vocab/cli\nnpm install --save @vocab/core @vocab/react\n```\n\n### Step 2: Configure Vocab\n\nYou can configure Vocab directly when calling the API, or via a `vocab.config.js` or `vocab.config.cjs` file.\n\n\u003e [!TIP]  \n\u003e It's a good idea to name your languages using [IETF language tags], however this is not a requirement.\n\nIn this example we've configured two languages named `en` (English) and `fr` (French).\nWe've also configured a `devLanguage` of `en`.\nThis is the language Vocab will assume when it sees a `translation.json` file without a language prefix.\n\n```js\n// vocab.config.js\nmodule.exports = {\n  languages: [{ name: 'en' }, { name: 'fr' }],\n  devLanguage: 'en'\n};\n```\n\nSee the [configuration] section for more configuration options.\n\n[IETF language tags]: https://en.wikipedia.org/wiki/IETF_language_tag\n[configuration]: #configuration\n\n### Step 3: Set the language using the React Provider\n\nVocab uses React's context API to provide information for your translation lookups.\nTo 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.\n\n\u003e [!NOTE]\n\u003e Using methods discussed later we'll make sure the first language is loaded on page load.\n\u003e However, after this, changing languages may lead to a period of no translations as Vocab downloads the new language's translations.\n\n```tsx\n// src/App.tsx\n\nimport { VocabProvider } from '@vocab/react';\n\nconst App = ({ children }) =\u003e {\n  return (\n    \u003cVocabProvider language=\"en\"\u003e{children}\u003c/VocabProvider\u003e\n  );\n};\n```\n\nIf you need to customize the locale for your language, you can pass a `locale` prop to the `VocabProvider` component.\nThis tells Vocab which locale to use when formatting your translations.\n\n```tsx\n// src/App.tsx\n\nimport { VocabProvider } from '@vocab/react';\n\nfunction App({ children }) {\n  return (\n    \u003cVocabProvider language=\"myCustomLanguage\" locale=\"en\"\u003e\n      {children}\n    \u003c/VocabProvider\u003e\n  );\n}\n```\n\nSee [here][overriding the locale] for more information on how and when to use the `locale` prop.\n\n[overriding the locale]: #overriding-the-locale\n\n### Step 4: Create translations\n\nA translation file is a JSON file consisting of a flat structure of keys.\nEach key must contain a `message` property, and optionally a `description` property.\n\nRather than creating one giant file for each language's translations, Vocab enables you to co-locate the translations alongside their consuming components.\nTo facilitate this, Vocab lets you group translations inside folders ending in `.vocab`.\nYou may have as many of these folders as you like in your project.\n\n\u003e [!TIP]\n\u003e Your folders can be named anything, as long as it ends in `.vocab`.\n\u003e It's recommened to just name your folders `.vocab` so you have one less name to think of/rename in the future.\n\nTranslation files must follow the naming pattern of `{languageName}.translations.json`.\nThe exception to this is translations for your `devLanguage` which must be placed in a file named `translations.json`.\n\nIn the following examples, we're defining translations for our `devLanguage`, and a language named `fr`.\n\n```jsonc\n// src/MyComponent/.vocab/translations.json\n\n{\n  \"my key\": {\n    \"message\": \"Hello from Vocab\",\n    \"description\": \"An optional description to help when translating\"\n  }\n}\n```\n\n```jsonc\n// src/MyComponent/.vocab/fr.translations.json\n\n{\n  \"my key\": {\n    \"message\": \"Bonjour de Vocab\",\n    \"description\": \"An optional description to help when translating\"\n  }\n}\n```\n\n\u003e [!NOTE]\n\u003e You can create your translation files manually.\n\u003e However, Vocab also offers integrations with remote translation platforms to push and pull translations automatically.\n\u003e See [External translation tooling] for more information.\n\n[External translation tooling]: #external-translation-tooling\n\n### Step 5: Compile and consume translations\n\nOnce you have created some translations, run `vocab compile`.\nThis command creates an `index.ts` file inside each folder ending in `.vocab`.\nImporting this file provides type-safe translations for your React components.\nAccessing translation messages is done by passing these imported translations to the `useTranslations` hook and using the returned `t` function.\n\n```tsx\n// src/MyComponent.tsx\n\nimport { useTranslations } from '@vocab/react';\nimport translations from './.vocab';\n\nfunction MyComponent({ children }) {\n  const { t } = useTranslations(translations);\n\n  // t('my key') will return the appropriate translation based on the language set in your app's VocabProvider\n  return \u003cdiv\u003e{t('my key')}\u003c/div\u003e;\n}\n```\n\n### Step 6: [Optional] Set up plugin\n\n#### Webpack Plugin\n\nWith the default setup, every language is loaded into your web application all the time, potentially leading to a large bundle size.\nIdeally you will want to switch out the Node.js/default runtime for the web runtime, which only loads the active language.\n\nThis is done using the `VocabWebpackPlugin`.\nApplying this plugin to your client webpack configuration will replace all vocab files with dynamic asynchronous chunks designed for the web.\n\n```sh\nnpm i --save-dev @vocab/webpack\n```\n\n```js\n// webpack.config.js\n\nconst { VocabWebpackPlugin } = require('@vocab/webpack');\n\nmodule.exports = {\n  plugins: [new VocabWebpackPlugin()]\n};\n```\n\n#### Vite Plugin _(this plugin is experimental)_\n\n\u003e [!NOTE]\n\u003e 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.\n\nVocab also provides a Vite plugin to handle the same functionality as the Webpack plugin.\n\n```shell\nnpm i --save-dev @vocab/vite\n```\n\ndefault usage\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport { vocabPluginVite } from '@vocab/vite';\nimport vocabConfig from './vocab.config.cjs';\n\nexport default defineConfig({\n  plugins: [\n    vocabPluginVite({\n      vocabConfig\n    })\n  ]\n});\n```\n\n#### createVocabChunks\n\nIf you want to combine all language files into a single chunk, you can use the `createVocabChunks` function.\nSimply use the function in your `manualChunks` configuration.\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport { vocabPluginVite } from '@vocab/vite';\nimport { createVocabChunks } from '@vocab/vite/create-vocab-chunks';\nimport vocabConfig from './vocab.config.cjs';\n\nexport default defineConfig({\n  plugins: [\n    vocabPluginVite({\n      vocabConfig\n    })\n  ],\n  build: {\n    rollupOptions: {\n      output: {\n        manualChunks: (id, ctx) =\u003e {\n          // handle your own manual chunks before or after the vocab chunks.\n          const languageChunkName = createVocabChunks(\n            id,\n            ctx\n          );\n          if (languageChunkName) {\n            // vocab has found a language chunk. Either return it or handle it in your own way.\n            return languageChunkName;\n          }\n        }\n      }\n    }\n  }\n});\n```\n\n#### VocabPluginOptions\n\n```ts\ntype VocabPluginOptions = {\n  /**\n   * The Vocab configuration file.\n   * The type can be found in the `@vocab/core/types`.\n   * This value is required\n   */\n  vocabConfig: UserConfig;\n};\n```\n\n### Step 7: [Optional] Optimize for fast page loading\n\nUsing 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.\n\nThis is where `getChunkName` can be used to retrieve the Webpack chunk used for a specific language.\n\nFor 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).\n\n```tsx\n// src/render.tsx\n\nimport { getChunkName } from '@vocab/webpack/chunk-name';\n\n// ...\n\nconst chunkName = getChunkName(language);\n\nconst extractor = new ChunkExtractor();\n\nextractor.addChunk(chunkName);\n```\n\n## Dynamic Values in Translations\n\nTranslation messages can sometimes contain dynamic values, such as dates/times, links, usernames, etc.\nThese values often exist somewhere in the middle of a message, and could change location depending on the translation.\nTo 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.\n\nIn the below example we are defining two messages: one that accepts a single parameter, and one that accepts a component.\n\n```json\n{\n  \"my key with param\": {\n    \"message\": \"Bonjour de {name}\"\n  },\n  \"my key with component\": {\n    \"message\": \"Bonjour de \u003cLink\u003eVocab\u003c/Link\u003e\"\n  }\n}\n```\n\nVocab will automatically parse these strings as ICU messages and generate strict types for any parameters it finds.\n\n```tsx\nt('my key with param', { name: 'Vocab' });\nt('my key with component', {\n  Link: (children) =\u003e \u003ca href=\"/foo\"\u003e{children}\u003c/a\u003e\n});\n```\n\n[Format.js's `intl-messageformat` library]: https://formatjs.github.io/docs/intl-messageformat/\n\n## Overriding the Locale\n\nBy default, your language name is passed as the `locale` to the formatting API provided by [`intl-messageformat`].\nThe `locale` is used to determine how to format dates, numbers, and other locale-sensitive values.\nIf you wish to customize this behaviour, you can pass a `locale` prop to the `VocabProvider` component.\n\n```tsx\n\u003cVocabProvider language=\"myCustomLanguage\" locale=\"th-TH\"\u003e\n  {children}\n\u003c/VocabProvider\u003e\n```\n\nThis can be useful in certain situations:\n\n- You have chosen to name your language something other than an [IETF language tag], but still want to use a specific locale for formatting\n- You want to use a different locale for formatting a specific language.\n  E.g. when formatting values for `th` (Thai) locales, the default calendar is Buddhist, but you may want to use the Gregorian calendar.\n  This can be achieved by specifying a `locale` value with a BCP 47 extension sequence suffix such as `-u-ca-gregory`.\n  For example: `th-u-ca-gregory`.\n  See the [MDN Intl docs] for more information on BCP 47 extension sequences.\n\n[`intl-messageformat`]: https://formatjs.github.io/docs/intl-messageformat/\n[IETF language tag]: https://en.wikipedia.org/wiki/IETF_language_tag\n[mdn intl docs]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument\n\n## Accessing the Current `language` or `locale`\n\nIf you need to access either the `language` or `locale` that you passed to your `VocabProvider`, you can use the `useLanguage` hook:\n\n```tsx\nimport { useLanguage } from '@vocab/react';\n\nconst MyComponent = () =\u003e {\n  const { language, locale } = useLanguage();\n  return (\n    \u003cdiv\u003e\n      {language} - {locale}\n    \u003c/div\u003e\n  );\n};\n```\n\n\u003e [!CAUTION]\\\n\u003e `locale` is only available when you pass a `locale` prop to your `VocabProvider`.\n\u003e If you don't pass a `locale` prop, `locale` will be `undefined`.\n\u003e It's generally advised to name your languages using [IETF language tags] and let Vocab handle the locale for you.\n\u003e This gives you the added benefit that you can use the `language` from `useLanguage` if necessary, and it will always be defined.\n\nTypically you won't need to access these values since the ICU message syntax supports locale-aware formatting of [numbers], [dates, and times].\nHowever, one use case where you might need to access these values is when formatting a currency value.\nThis is because there is currently no way to specify the currency for an ICU message programmatically, so it must be hardcoded within the messsage.\nThis poses a problem when you don't want to couple your translations to a specific currency.\n\n```json\n{\n  \"my key with currency\": {\n    \"message\": \"You have {value, number, ::compact-short currency/GBP}\"\n  }\n}\n```\n\nWhen given a `value` of `123`, the above message would render as `You have GBP 123`.\n\nTo 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:\n\n```tsx\nconst Currency = ({ value, currency }) =\u003e {\n  const { language } = useLanguage();\n\n  const formattedValue = new Intl.NumberFormat(locale, {\n    style: 'currency',\n    currency\n  }).format(value);\n\n  return \u003cdiv\u003e{formattedValue}\u003c/div\u003e;\n};\n```\n\n[numbers]: https://formatjs.github.io/docs/core-concepts/icu-syntax/#number-type\n[dates, and times]: https://formatjs.github.io/docs/core-concepts/icu-syntax/#supported-datetime-skeleton\n\n## Configuration\n\nConfiguration can either be passed into the Node API directly or be gathered from the nearest `vocab.config.js` or `vocab.config.cjs` file.\n\n```js\n// vocab.config.js\n\nfunction capitalize(element) {\n  return element.toUpperCase();\n}\n\nfunction pad(message) {\n  return '[' + message + ']';\n}\n\nmodule.exports = {\n  devLanguage: 'en',\n  languages: [\n    { name: 'en' },\n    { name: 'en-AU', extends: 'en' },\n    { name: 'en-US', extends: 'en' },\n    { name: 'fr-FR' }\n  ],\n  /**\n   * An array of languages to generate based off translations for existing languages\n   * Default: []\n   */\n  generatedLanguages: [\n    {\n      name: 'generatedLanguage',\n      extends: 'en',\n      generator: {\n        transformElement: capitalize,\n        transformMessage: pad\n      }\n    }\n  ],\n  /**\n   * The root directory to compile and validate translations\n   * Default: Current working directory\n   */\n  projectRoot: './example/',\n  /**\n   * A custom suffix to name vocab translation directories\n   * Default: '.vocab'\n   */\n  translationsDirectorySuffix: '.vocab',\n  /**\n   * An array of glob paths to ignore from compilation and validation\n   */\n  ignore: ['**/ignored_directory/**']\n};\n```\n\n## Translation Key Types\n\nIf you need to access the keys of your translations as a TypeScript type, you can use the `TranslationKeys` type from `@vocab/core`:\n\n```jsonc\n// translations.json\n{\n  \"Hello\": {\n    \"message\": \"Hello\"\n  },\n  \"Goodbye\": {\n    \"message\": \"Goodbye\"\n  }\n}\n```\n\n```ts\nimport type { TranslationKeys } from '@vocab/core';\nimport translations from './.vocab';\n\n// \"Hello\" | \"Goodbye\"\ntype MyTranslationKeys = TranslationKeys\u003c\n  typeof translations\n\u003e;\n```\n\n## Generated languages\n\nVocab supports the creation of generated languages via the `generatedLanguages` config.\n\nGenerated languages are created by running a message `generator` over every translation message in an existing translation.\nA `generator` may contain a `transformElement` function, a `transformMessage` function, or both.\nBoth of these functions accept a single string parameter and return a string.\n\n`transformElement` is applied to string literal values contained within `MessageFormatElement`s.\nA `MessageFormatElement` is an object representing a node in the AST of a compiled translation message.\nSimply 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`.\nAn 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.\n\n`transformMessage` receives the entire translation message _after_ `transformElement` has been applied to its individual elements.\nAn 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.\n\nBy 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.\n\n```js\n// vocab.config.js\n\nfunction capitalize(message) {\n  return message.toUpperCase();\n}\n\nfunction pad(message) {\n  return '[' + message + ']';\n}\n\nmodule.exports = {\n  devLanguage: 'en',\n  languages: [{ name: 'en' }, { name: 'fr' }],\n  generatedLanguages: [\n    {\n      name: 'generatedLanguage',\n      extends: 'en',\n      generator: {\n        transformElement: capitalize,\n        transformMessage: pad\n      }\n    }\n  ]\n};\n```\n\nGenerated languages are consumed the same way as regular languages.\nAny Vocab API that accepts a `language` parameter will work with a generated language as well as a regular language.\n\n```tsx\n// App.tsx\n\nconst App = () =\u003e (\n  \u003cVocabProvider language=\"generatedLanguage\"\u003e\n    \u003cdiv\u003eHello, world!\u003c/div\u003e\n  \u003c/VocabProvider\u003e\n);\n```\n\n[icu message syntax]: https://formatjs.github.io/docs/intl-messageformat/#message-syntax\n[diacritics]: https://en.wikipedia.org/wiki/Diacritic\n\n## Pseudo-localization\n\nThe `@vocab/pseudo-localize` package exports low-level functions that can be used for pseudo-localization of translation messages.\n\n```sh\n$ npm install --save-dev @vocab/pseudo-localize\n```\n\n```ts\nimport {\n  extendVowels,\n  padString,\n  pseudoLocalize,\n  substituteCharacters\n} from '@vocab/pseudo-localize';\n\nconst message = 'Hello';\n\n// [Hello]\nconst paddedMessage = padString(message);\n\n// Ḩẽƚƚö\nconst substitutedMessage = substituteCharacters(message);\n\n// Heelloo\nconst extendedMessage = extendVowels(message);\n\n// Extend the message and then substitute characters\n// Ḩẽẽƚƚöö\nconst pseudoLocalizedMessage = pseudoLocalize(message);\n```\n\nPseudo-localization is a transformation that can be applied to a translation message.\nVocab's implementation of this transformation contains the following elements:\n\n- _Start and end markers (`padString`):_ All strings are encapsulated in `[` and `]`.\n\n  If a developer doesn’t see these characters they know the string has been clipped by an inflexible UI element.\n\n- _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).\n\n- _Padding text (`extendVowels`):_ Simulates translation-induced expansion.\n\n  Vocab's implementation of this involves repeating vowels (and `y`) to simulate a 40% expansion in the message's length.\n\nThis [Netflix technology blog post] inspired Vocab's implementation of this functionality.\n\n[netflix technology blog post]: https://netflixtechblog.com/pseudo-localization-netflix-12fff76fbcbe\n\n### Generating a pseudo-localized language using Vocab\n\nVocab 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.\n`@vocab/pseudo-localize` exports a `generator` that can be used directly in your config.\n\n```js\n// vocab.config.js\n\nconst { generator } = require('@vocab/pseudo-localize');\n\nmodule.exports = {\n  devLanguage: 'en',\n  languages: [{ name: 'en' }, { name: 'fr' }],\n  generatedLanguages: [\n    {\n      name: 'pseudo',\n      extends: 'en',\n      generator\n    }\n  ]\n};\n```\n\n[generated languages config]: #generated-languages\n\n## Use Without React\n\nIf you need to use Vocab outside of React, you can access the translations directly.\nYou'll then be responsible for when to load translations and how to update on translation load.\n\n#### Async access\n\n- `getMessages(language: string) =\u003e Promise\u003cMessages\u003e` returns messages for the given language formatted according to the correct locale.\n  If the language has not been loaded it will load the language before resolving.\n\n\u003e [!NOTE]\n\u003e To optimize loading time you may want to call [`load`] ahead of use.\n\n[`load`]: #sync-access\n\n#### Sync access\n\n- `load(language: string) =\u003e Promise\u003cvoid\u003e` attempts to pre-load messages for the given language, resolving once loaded.\n  This function only ensures the language is available and does not return any translations.\n- `getLoadedMessages(language: string) =\u003e Messages | null` returns messages for the given language formatted according to the correct locale.\n  If the language has not been loaded it will return `null`.\n  This will not load a language that is not available.\n  Useful when a synchronous (non-promise) return is required.\n\n**Example: Promise based formatting of messages**\n\n```ts\nimport translations from './.vocab';\n\nasync function getFooMessage(language) {\n  let messages = await translations.getMessages(language);\n  return messages['my key'].format();\n}\n\ngetFooMessage().then((m) =\u003e console.log(m));\n```\n\n**Example: Synchronously returning a message**\n\n```ts\nimport translations from './.vocab';\n\nfunction getFooMessageSync(language) {\n  let messages = translations.getLoadedMessages(language);\n  if (!messages) {\n    // Translations not loaded, start loading and return null for now\n    translations.load();\n    return null;\n  }\n  return messages.foo.format();\n}\n\ntranslations.load();\n\nconst onClick = () =\u003e {\n  console.log(getFooMessageSync());\n};\n```\n\n## Generate Types\n\nVocab generates custom `index.ts` files that give your React components strongly typed translations to work with.\n\nTo generate these files run:\n\n```sh\nvocab compile\n```\n\nOr to re-run the compiler when files change:\n\n```sh\nvocab compile --watch\n```\n\n## External Translation Tooling\n\nVocab can be used to synchronize your translations with translations from a remote translation platform.\n\n| Platform | Environment Variables               |\n| -------- | ----------------------------------- |\n| [Phrase] | PHRASE_PROJECT_ID, PHRASE_API_TOKEN |\n\n```sh\nvocab push --branch my-branch\nvocab pull --branch my-branch\n```\n\n### [Phrase] Platform Features\n\n#### Delete Unused keys\n\nWhen uploading translations, Phrase identifies keys that exist in the Phrase project, but were not\nreferenced in the upload. These keys can be deleted from Phrase by providing the\n`--delete-unused-keys` flag to `vocab push`. E.g.\n\n```sh\nvocab push --branch my-branch --delete-unused-keys\n```\n\n#### Ignoring Files\n\nThe `ignore` key in your [Vocab config](#configuration) allows you to ignore certain files from being validated, compiled and uploaded.\nHowever, 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.\nThis can be accomplished by providing the `--ignore` flag to `vocab push`.\nThis flag accepts an array of glob patterns to ignore.\n\n```sh\nvocab push --branch my-branch --ignore \"**/dist/**\" \"**/another_ignored_directory/**\"\n```\n\n#### Auto-Translation\n\nBy default, Phrase may not apply the project's automatic translation behaviour for new keys uploaded via API.\n\nThe `--auto-translate` flag instructs Phrase to automatically translate any missing keys using machine translation.. See [Phrase auto-translate API Documentation] for more information.\n\n```sh\nvocab push --branch my-branch --auto-translate\n```\n\n[Phrase auto-translate API Documentation]: https://developers.phrase.com/en/api/strings/uploads/upload-a-new-file#body-autotranslate\n[phrase]: https://developers.phrase.com/api/\n\n#### [Tags]\n\n`vocab push` supports uploading [tags] to Phrase.\n\nTags can be added to an individual key via the `tags` property:\n\n```jsonc\n// translations.json\n\n{\n  \"Hello\": {\n    \"message\": \"Hello\",\n    \"tags\": [\"greeting\", \"home_page\"]\n  },\n  \"Goodbye\": {\n    \"message\": \"Goodbye\",\n    \"tags\": [\"home_page\"]\n  }\n}\n```\n\nTags can also be added under a top-level `_meta` field. This will result in the tags applying to all\nkeys specified in the file:\n\n```jsonc\n// translations.json\n\n{\n  \"_meta\": {\n    \"tags\": [\"home_page\"]\n  },\n  \"Hello\": {\n    \"message\": \"Hello\",\n    \"tags\": [\"greeting\"]\n  },\n  \"Goodbye\": {\n    \"message\": \"Goodbye\"\n  }\n}\n```\n\nIn the above example, both the `Hello` and `Goodbye` keys would have the `home_page` tag attached to\nthem, but only the `Hello` key would have the `usage_greeting` tag attached to it.\n\n\u003e [!NOTE]\n\u003e Only tags specified on keys in your [`devLanguage`][configuration] will be uploaded.\n\u003e Tags on keys in other languages will be ignored.\n\n[tags]: https://support.phrase.com/hc/en-us/articles/5822598372252-Tags-Strings-\n[configuration]: #configuration\n\n#### Global key\n\n`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.\n\n```jsonc\n// translations.json\n\n{\n  \"Hello\": {\n    \"message\": \"Hello\",\n    \"globalKey\": \"hello\"\n  },\n  \"Goodbye\": {\n    \"message\": \"Goodbye\",\n    \"globalKey\": \"app.goodbye.label\"\n  }\n}\n```\n\nIn the above example,\n\n- `vocab push` will push the `hello` and `app.goodbye.label` keys to Phrase.\n- `vocab pull` will pull translations from Phrase and map them to the `hello` and `app.goodbye.label` keys.\n\n##### Error on no translation for global key\n\nBy default, `vocab pull` will not error if a translation is missing in Phrase for a translation with a global key.\nIf you want to throw an error in this situation, pass the `--error-on-no-global-key-translation` flag:\n\n```sh\nvocab pull --error-on-no-global-key-translation\n```\n\n## Troubleshooting\n\n### Problem: Passed locale is being ignored or using en-US instead\n\nWhen running in Node.js, the locale formatting is supported by [Node.js's Internationalization support](https://nodejs.org/api/intl.html#intl_internationalization_support).\nNode.js will silently switch to the closest locale it can find if the passed locale is not available.\nSee 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseek-oss%2Fvocab","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseek-oss%2Fvocab","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseek-oss%2Fvocab/lists"}