{"id":13520429,"url":"https://github.com/andreasbm/lit-translate","last_synced_at":"2025-04-06T08:13:15.177Z","repository":{"id":41380744,"uuid":"152460737","full_name":"andreasbm/lit-translate","owner":"andreasbm","description":"A blazing-fast and lightweight internationalization (i18n) library for your next web-based project","archived":false,"fork":false,"pushed_at":"2022-12-26T16:00:47.000Z","size":10643,"stargazers_count":136,"open_issues_count":20,"forks_count":14,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-05-02T00:52:04.302Z","etag":null,"topics":["i18n","internationalization","lit","lit-element","lit-html","localization","pwa","translate","translation","webapp"],"latest_commit_sha":null,"homepage":"https://codepen.io/andreasbm/pen/MWWXPNO?editors=1010","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/andreasbm.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-10T17:11:48.000Z","updated_at":"2024-03-15T21:53:48.000Z","dependencies_parsed_at":"2023-01-31T00:30:51.321Z","dependency_job_id":null,"html_url":"https://github.com/andreasbm/lit-translate","commit_stats":null,"previous_names":[],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasbm%2Flit-translate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasbm%2Flit-translate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasbm%2Flit-translate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasbm%2Flit-translate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andreasbm","download_url":"https://codeload.github.com/andreasbm/lit-translate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247451665,"owners_count":20940944,"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","lit","lit-element","lit-html","localization","pwa","translate","translation","webapp"],"created_at":"2024-08-01T05:02:20.423Z","updated_at":"2025-04-06T08:13:15.155Z","avatar_url":"https://github.com/andreasbm.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"\u003c!-- ⚠️ This README has been generated from the file(s) \"blueprint.md\" ⚠️--\u003e\u003ch1 align=\"center\"\u003elit-translate\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https://codepen.io/andreasbm/pen/MWWXPNO?editors=1010\"\u003e\n      \u003cimg src=\"https://raw.githubusercontent.com/andreasbm/lit-translate/master/example.gif\" width=\"650\" style=\"max-width: 100%;\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\t\t\u003ca href=\"https://npmcharts.com/compare/lit-translate?minimal=true\"\u003e\u003cimg alt=\"Downloads per month\" src=\"https://img.shields.io/npm/dm/lit-translate.svg\" height=\"20\"/\u003e\u003c/a\u003e\r\n\u003ca href=\"https://www.npmjs.com/package/lit-translate\"\u003e\u003cimg alt=\"NPM Version\" src=\"https://img.shields.io/npm/v/lit-translate.svg\" height=\"20\"/\u003e\u003c/a\u003e\r\n\u003ca href=\"https://david-dm.org/andreasbm/lit-translate\"\u003e\u003cimg alt=\"Dependencies\" src=\"https://img.shields.io/david/andreasbm/lit-translate.svg\" height=\"20\"/\u003e\u003c/a\u003e\r\n\u003ca href=\"https://github.com/andreasbm/lit-translate/graphs/contributors\"\u003e\u003cimg alt=\"Contributors\" src=\"https://img.shields.io/github/contributors/andreasbm/lit-translate.svg\" height=\"20\"/\u003e\u003c/a\u003e\r\n\u003ca href=\"https://www.webcomponents.org/element/lit-translate\"\u003e\u003cimg alt=\"Published on webcomponents.org\" src=\"https://img.shields.io/badge/webcomponents.org-published-blue.svg\" height=\"20\"/\u003e\u003c/a\u003e\r\n\u003ca href=\"https://github.com/web-padawan/awesome-lit-html\"\u003e\u003cimg alt=\"undefined\" src=\"https://awesome.re/badge.svg\" height=\"20\"/\u003e\u003c/a\u003e\n\t\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cb\u003eA blazing-fast and lightweight internationalization (i18n) library for your next web-based project\u003c/b\u003e\u003c/br\u003e\n  \u003csub\u003e\u003csub\u003e\n\u003c/p\u003e\n\n\u003cbr /\u003e\n\n\n* Contains a [lit](https://www.npmjs.com/package/lit) directive that automatically updates the translations when the language changes\r\n* Has a simple API that can return a translation for a given key using the dot notation (eg. `get(\"home.header.title\")`)\r\n* Works very well with JSON based translation data-structures\r\n* Can interpolate values into the strings using the {{ key }} syntax out of the box\r\n* Caches the translations for maximum performance\r\n* Has a very small footprint, approximately 800 bytes minified \u0026 gzipped (2kb without)\r\n* Extremely customizable, just about everything can be changed (eg. choose your own translations loader, how to interpolate values, empty placeholder and how to look up the strings)\r\n* Check out the playground [here](https://codepen.io/andreasbm/pen/MWWXPNO?editors=1010)\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#table-of-contents)\r\n\r\n## ➤ Table of Contents\n\n* [➤ Installation](#-installation)\r\n* [➤ 1. Define the translations](#-1-define-the-translations)\r\n* [➤ 2. Register the translate config](#-2-register-the-translate-config)\r\n* [➤ 3. Set the language](#-3-set-the-language)\r\n* [➤ 4. Get the translations](#-4-get-the-translations)\r\n* [➤ 5. Interpolate values](#-5-interpolate-values)\r\n* [➤ 6. Use the `translate` directive with `lit`](#-6-use-the-translate-directive-with-lit)\r\n* [➤ Wait for strings to be loaded before displaying your app](#-wait-for-strings-to-be-loaded-before-displaying-your-app)\r\n* [➤ Advanced Customisation](#-advanced-customisation)\r\n\t* [Format text with `IntlMessageFormat`](#format-text-with-intlmessageformat)\r\n\t* [Use the default translations as keys](#use-the-default-translations-as-keys)\r\n* [➤ Typesafe Translations](#-typesafe-translations)\r\n\t* [1. Add `resolveJsonModule` to your tsconfig](#1-add-resolvejsonmodule-to-your-tsconfig)\r\n\t* [2. Use the `typedKeysFactory` function](#2-use-the-typedkeysfactory-function)\r\n\t* [3. Import the typed functions](#3-import-the-typed-functions)\r\n* [➤ `lit` Directives](#-lit-directives)\r\n\t* [Re-render a value when the language changes with the `langChanged` directive](#re-render-a-value-when-the-language-changes-with-the-langchanged-directive)\r\n\t* [Create your own `lit` directives that re-renders a value when the language changes](#create-your-own-lit-directives-that-re-renders-a-value-when-the-language-changes)\r\n* [➤ License](#-license)\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#installation)\r\n\r\n## ➤ Installation\n\n```js\nnpm i lit-translate\n```\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#1-define-the-translations)\r\n\r\n## ➤ 1. Define the translations\n\nCreate a `.json` file for each language you want to support. Heres an example of how `en.json` could look like.\n\n```json\n{\n  \"header\": {\n    \"title\": \"Hello\",\n    \"subtitle\": \"World\"\n  },\n  \"cta\": {\n    \"awesome\": \"{{ animals }} are awesome!\",\n    \"cats\": \"Cats\"\n  },\n  \"footer\": {\n    \"html\": \"\u003cb\u003eBold text\u003c/b\u003e\"\n  }\n}\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#2-register-the-translate-config)\r\n\r\n## ➤ 2. Register the translate config\n\nUse the `registerTranslateConfig` function to register a loader that loads translations based on the selected language. In the example below, a loader is registered that uses the [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to load a `.json` file for the selected language.\n\n```typescript\nimport { registerTranslateConfig } from \"lit-translate\";\n\nregisterTranslateConfig({\n  loader: lang =\u003e fetch(`${lang}.json`).then(res =\u003e res.json())\n});\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#3-set-the-language)\r\n\r\n## ➤ 3. Set the language\n\nSet the language with the `use` function. When called it will use the registered loader from [step 2](#-2-register-the-translate-config) to load the strings for the selected language.\n\n```typescript\nimport { use } from \"lit-translate\";\n\nuse(\"en\");\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#4-get-the-translations)\r\n\r\n## ➤ 4. Get the translations\n\nGet translations with the `get` function. Give this function a string of keys (separated with `.`) that points to the desired translation in the JSON structure. The example below is based on the translations defined in [step 1](#-1-define-the-translations) and registered in [step 2](#-2-register-the-translate-config).\n\n```typescript\nimport { get } from \"lit-translate\";\n\nget(\"header.title\"); // \"Hello\"\nget(\"header.subtitle\"); // \"World\"\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#5-interpolate-values)\r\n\r\n## ➤ 5. Interpolate values\n\nWhen using the `get` function it is possible to interpolate values (replacing placeholders with content). As default, you can use the `{{ key }}` syntax in your translations and provide an object with values replacing those defined in the translations when using the `get` function. The example below is based on the strings defined in [step 1](#-1-define-the-translations) and registered in [step 2](#-2-register-the-translate-config).\n\n```typescript\nimport { get } from \"lit-translate\";\n\nget(\"cta.awesome\", { animals: get(\"cta.cats\") }); // Cats are awesome!\n```\n\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#6-use-the-translate-directive-with-lit)\r\n\r\n## ➤ 6. Use the `translate` directive with `lit`\n\nIf you are using [lit](https://www.npmjs.com/package/lit) you might want to use the `translate` directive. This directive makes sure to automatically update all the translated parts when the `use` function is called with a new language. If your strings contain HTML you can use the `translateUnsafeHTML` directive. The example below is based on the strings defined in [step 1](#-1-define-the-translations) and registered in [step 2](#-2-register-the-translate-config).\n\n```typescript\nimport { translate, translateUnsafeHTML } from \"lit-translate\";\nimport { LitElement, html } from \"lit\";\nimport { customElement } from \"lit/decorators.js\";\n\n@customElement(\"my-element\")\nclass MyElement extends LitElement {\n  render () {\n    html`\n      \u003ch1\u003e${translate(\"header.title\")}\u003c/h1\u003e\n      \u003cp\u003e${translate(\"header.subtitle\")}\u003c/p\u003e\n      \u003cspan\u003e${translate(\"cta.awesome\", { animals: () =\u003e get(\"cta.cats\") })}\u003c/span\u003e\n      \u003cspan\u003e${translateUnsafeHTML(\"footer.html\")}\u003c/span\u003e\n    `;\n  }\n}\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#wait-for-strings-to-be-loaded-before-displaying-your-app)\r\n\r\n## ➤ Wait for strings to be loaded before displaying your app\n\nYou might want to avoid empty placeholders being shown initially before any of the translation strings have been loaded. This it how you could defer the first render of your app until the strings have been loaded.\n\n```typescript\nimport { use, translate } from \"lit-translate\";\nimport { LitElement, html, PropertyValues } from \"lit\";\nimport { customElement, state } from \"lit/decorators.js\";\n\n@customElement(\"my-app\")\nexport class MyApp extends LitElement {\n  \n  // Defer the first update of the component until the strings has been loaded to avoid empty strings being shown\n  @state() hasLoadedStrings = false;\n\n  protected shouldUpdate(props: PropertyValues) {\n    return this.hasLoadedStrings \u0026\u0026 super.shouldUpdate(props);\n  }\n\n  // Load the initial language and mark that the strings has been loaded so the component can render.\n  async connectedCallback() {\n    super.connectedCallback();\n\n    await use(\"en\");\n    this.hasLoadedStrings = true;\n  }\n\n  // Render the component\n  protected render () {\n    return html`\n      \u003cp\u003e${translate(\"title\")}\u003c/p\u003e\n    `;\n  }\n}\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#advanced-customisation)\r\n\r\n## ➤ Advanced Customisation\n\nIf you want you can customise just about anything by overwriting the configuration hooks. Below is an example of what you can customise. Try it as a playground [here](https://codepen.io/andreasbm/pen/gOoVGdQ?editors=0010).\n\n```typescript\nimport { registerTranslateConfig, extract, get, use } from \"lit-translate\";\n\nregisterTranslateConfig({\n\n  // Loads the language by returning a JSON structure for a given language\n  loader: lang =\u003e {\n    switch (lang) {\n\n      // English strings\n      case \"en\":\n        return {\n          app: {\n            title: \"This is a title\",\n            description: \"This description is {placeholder}!\"\n          },\n          awesome: \"awesome\"\n        };\n\n      // Danish strings\n      case \"da\":\n        return {\n          app: {\n            title: \"Dette er en titel\",\n            description: \"Denne beskrivelse er {placeholder}!\"\n          },\n          awesome: \"fed\"\n        };\n        \n      default:\n        throw new Error(`The language ${lang} is not supported..`);\n    }\n  },\n\n  // Interpolate the values using a key syntax.\n  interpolate: (text, values) =\u003e {\n    for (const [key, value] of Object.entries(extract(values || {}))) {\n      text = text.replace(new RegExp(`{.*${key}.*}`, `gm`), String(extract(value)));\n    }\n\n\n    return text;\n  },\n\n  // Returns a string for a given key\n  lookup: (key, config) =\u003e {\n\n    // Split the key in parts (example: hello.world)\n    const parts = key.split(\" -\u003e \");\n\n    // Find the string by traversing through the strings matching the chain of keys\n    let string = config.strings;\n\n    // Shift through all the parts of the key while matching with the strings.\n    // Do not continue if the string is not defined or if we have traversed all the key parts\n    while (string != null \u0026\u0026 parts.length \u003e 0) {\n      string = string[parts.shift()];\n    }\n\n    // Make sure the string is in fact a string!\n    return string != null ? string.toString() : null;\n  },\n\n  // Formats empty placeholders (eg. !da.headline.title!) if lookup returns null\n  empty: (key, config) =\u003e `!${config.lang}.${key}!`\n});\n\nuse(\"en\").then(() =\u003e {\n  get(\"app -\u003e description\", { placeholder: get(\"awesome\") }); // Will return \"This description is awesome\"\n});\n```\n\n### Format text with `IntlMessageFormat`\n\n[IntlMessageFormat](https://www.npmjs.com/package/intl-messageformat) is a library that formats ICU message strings with number, date, plural, and select placeholders to create localized messages using [ICU placeholders](https://unicode-org.github.io/icu/userguide/format_parse/messages/). This library is a good addition to `lit-translate`. You can add it to the interpolate hook to get the benefits as shown in the following example. Try the example as a playground [here](https://codepen.io/andreasbm/pen/rNpXGPW?editors=0010).\n\n```typescript\nimport { registerTranslateConfig, extract } from \"lit-translate\";\nimport { IntlMessageFormat } from \"intl-messageformat\";\n\nregisterTranslateConfig({\n  loader: lang =\u003e {\n    switch (lang) {\n      case \"en\":\n        return {\n          photos: `You have {numPhotos, plural, =0 {no photos.} =1 {one photo.} other {# photos.}}`\n        };\n    \n      case \"en\":\n        return {\n          photos: `Du har {numPhotos, plural, =0 {ingen billeder.} =1 {et billede.} other {# billeder.}}`\n        };\n    \n      default:\n        throw new Error(`The language ${lang} is not supported..`);\n    }\n  },\n\n  // Use the \"intl-messageformat\" library for formatting.\n  interpolate: (text, values, config) =\u003e {\n    const msg = new IntlMessageFormat(text, config.lang);\n    return msg.format(extract(values));\n  }\n});\n\nuse(\"en\").then(() =\u003e {\n  get(\"photos\", {numPhotos: 0}); // Will return \"You have no photos\"\n  get(\"photos\", {numPhotos: 1}); // Will return \"You have one photo.\"\n  get(\"photos\", {numPhotos: 5}); // Will return \"You have 5 photos.\"\n});\n```\n\n### Use the default translations as keys\n\nInspired by [GNU gettext](https://en.wikipedia.org/wiki/Gettext) you can use the default translation as keys. The benefit of doing this is that you will save typing time and reduce code clutter. You can use [xgettext](https://www.gnu.org/software/gettext/manual/html_node/xgettext-Invocation.html) to extract the translatable strings from your code and then use [po2json](https://github.com/mikeedwards/po2json) to turn your `.po` files into `.json` files. The following code shows an example of how you could implement this. Try it as a playground [here](https://codepen.io/andreasbm/pen/RwxXjJX?editors=0010).\n\n```typescript\nimport { registerTranslateConfig, use, get } from \"lit-translate\";\n\nregisterTranslateConfig({\n  loader: lang =\u003e {\n    switch (lang) {\n      case \"da\":\n        return {\n          \"The page is being loaded...\": \"Siden indlæses...\"\n        };\n      default:\n        return {};\n    }\n  },\n  lookup: (key, config) =\u003e config.strings != null \u0026\u0026 config.strings[key] != null ? config.strings[key].toString() : key,\n  empty: key =\u003e key,\n});\n\nget(\"The page is being loaded...\"); // Will return \"The page is being loaded...\"\n\nuse(\"da\").then(() =\u003e {\n  get(\"The page is being loaded...\"); // Will return \"Siden indlæses...\"\n});\n```\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#typesafe-translations)\r\n\r\n## ➤ Typesafe Translations\n\n\u003cimg src=\"https://raw.githubusercontent.com/andreasbm/lit-translate/master/typesafe.gif\" width=\"450\"\u003e\n\nIf you have a lot of translation keys you can quickly lose the overview of your strings. If you use Typescript you can make the keys of your translation keys typesafe - this will also give you autocompletion when you enter the keys. To achieve this you have to do the following:\n\n\n### 1. Add `resolveJsonModule` to your tsconfig\n\nAdd [resolveJsonModule](https://www.typescriptlang.org/tsconfig#resolveJsonModule) to your `tsconfig` which will allow us to import modules with a `.json` extension.\n\n```json\n{\n  ...\n  \"compilerOptions\": {\n    ...\n    \"resolveJsonModule\": true\n  }\n}\n```\n\n### 2. Use the `typedKeysFactory` function\n\nCreate a file, for example `typed-lit-translate.ts`. Then use the factory function `typedKeysFactory` and provide it with the type of one of your translation files. Use `typeof import(..)` to import the `.json` file and get the type. Provide this type to the factory function, and it will return a version of `get`, `translate` and `translateUnsafeHTML` where the keys are typed. Export these and make sure to import from your `typed-lit-translate.ts` file instead of `lit-translate`. \n\n```typescript\n// typed-lit-translate.ts\nimport { typedKeysFactory } from \"lit-translate\";\n\nconst { get, translate, translateUnsafeHTML } = typedKeysFactory\u003ctypeof import(\"en.json\")\u003e();\nexport { get, translate, translateUnsafeHTML };\n```\n\n### 3. Import the typed functions\n\nMake sure to import the typed versions of `get`, `translate` and `translateUnsafeHTML` that you have created instead of importing from `lit-translate`.\n\n```typescript\nimport { get } from \"typed-lit-translate.ts\";\n\nget(\"this.key.is.typed\");\n```\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#lit-directives)\r\n\r\n## ➤ `lit` Directives\n\n### Re-render a value when the language changes with the `langChanged` directive\n\nUse the `langChanged` directive to re-render a value when the language changes.\n\n```typescript\nimport { langChanged, translateConfig } from \"lit-translate\";\nimport { html, LitElement, TemplateResult } from \"lit\";\nimport { customElement } from \"lit/decorators.js\";\n\n@customElement(\"my-component\")\nexport class MyComponent extends LitElement {\n  protected render(): TemplateResult {\n    return html`\n      \u003cimg src=\"${langChanged(() =\u003e `img-${translateConfig.lang || \"en\"}.png`)}\" /\u003e\n    `;\n  }\n}\n```\n\n### Create your own `lit` directives that re-renders a value when the language changes\n\nExtend the `LangChangedDirectiveBase` base class to create your own directives that re-renders a value when the language changes. Below is an example of a directive that localizes assets paths based on the selected language.\n\n```typescript\nimport { LangChangedDirectiveBase, translateConfig } from \"lit-translate\";\nimport { directive } from \"lit/directive.js\";\n\nexport const localizeAssetPath = directive(class extends LangChangedDirectiveBase {\n  render (fileName: string, config = translateConfig) {\n    return this.renderValue(() =\u003e `localized-assets/${config.lang || \"en\"}/${fileName}`);\n  }\n});\n```\n\n\r\n[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/rainbow.png)](#license)\r\n\r\n## ➤ License\n\t\nLicensed under [MIT](https://opensource.org/licenses/MIT).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreasbm%2Flit-translate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandreasbm%2Flit-translate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreasbm%2Flit-translate/lists"}