# Lingui
> Lingui is a lightweight, open-source internationalization (i18n) library for JavaScript and TypeScript. It brings compile-time macros and a CLI for message extraction to React, React Native, Vue, SolidJS, Astro, Svelte, and Node.js.
## Introduction
- [Introduction](https://lingui.dev/introduction.md): What Lingui is and how it works. A lightweight i18n library for JavaScript and TypeScript with compile-time macros and a message extraction CLI
## Installation
- [Installation and Setup](https://lingui.dev/installation.md): Learn how to install Lingui in your project
## Tutorials
- [JavaScript Apps Internationalization](https://lingui.dev/tutorials/javascript.md): Learn how to use Lingui's internationalization features in your vanilla JavaScript application
- [React Apps Internationalization](https://lingui.dev/tutorials/react.md): Learn how to add internationalization to a React application using Lingui
- [React Native Apps Internationalization](https://lingui.dev/tutorials/react-native.md): Learn how to add internationalization to a React Native application using Lingui
- [Next.js App Router i18n with React Server Components](https://lingui.dev/tutorials/react-rsc.md): Add internationalization to a Next.js App Router app with Lingui. Set up the SWC plugin, load catalogs in server and client components and switch languages
- [Solid Apps Internationalization](https://lingui.dev/tutorials/solid.md): Learn how to add internationalization to a SolidJS application using Lingui
- [Vue Apps Internationalization](https://lingui.dev/tutorials/vue.md): Learn how to add internationalization to a Vue 3 application using Lingui
## Guides
- [Custom Extractor](https://lingui.dev/guides/custom-extractor.md): Learn how to write a custom message extractor for your project
- [Custom Formatter](https://lingui.dev/guides/custom-formatter.md): Learn how to write a custom localization message formatter for your project
- [Dynamic Loading of Message Catalogs](https://lingui.dev/guides/dynamic-loading-catalogs.md): Learn how to set up dynamic loading of message catalogs in Lingui to reduce bundle size and improve performance
- [Explicit vs Generated IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md): Compare explicit and generated message IDs in Lingui i18n, understand the trade-offs, and choose the best approach for your localization workflow
- [Lazy Translations](https://lingui.dev/guides/lazy-translations.md): Lazy translations allow you to defer translation of a message until it is actually displayed
- [Message Extraction](https://lingui.dev/guides/message-extraction.md): Learn about message extraction in i18n and how to use Lingui to extract messages from your application
- [ICU MessageFormat](https://lingui.dev/guides/message-format.md): The ICU MessageFormat syntax Lingui uses for messages. Variables, plurals, select and ordinals explained with examples
- [Monorepo](https://lingui.dev/guides/monorepo.md): How to organize message catalogs, extraction and the shared runtime when Lingui is used across several apps and packages in a monorepo
- [Keeping Your Bundle Small: How Lingui Optimizes for Performance](https://lingui.dev/guides/optimizing-bundle-size.md): How Lingui keeps your bundle small by compiling messages to compact IDs and dropping the message compiler in production, and how to configure that behavior
- [Pluralization](https://lingui.dev/guides/plurals.md): Learn about pluralization and how to use it in your application with Lingui
- [Pseudolocalization](https://lingui.dev/guides/pseudolocalization.md): Learn how to use pseudolocalization to test the internationalization aspects of your application with Lingui
- [Testing](https://lingui.dev/guides/testing.md): How to test React components that use Trans or useLingui by wrapping them in I18nProvider with React Testing Library
- [Translator-friendly Messages](https://lingui.dev/guides/translator-friendly-messages.md): Write Lingui messages that give translators and AI the context they need - whole sentences, named placeholders and tags, comments, and context - and enforce it with ESLint
- [Typed Message IDs](https://lingui.dev/guides/typed-message-ids.md): Learn how to opt in to type-safe message IDs for autocomplete and compile-time validation
## API Reference
- [Catalog Formats](https://lingui.dev/ref/catalog-formats.md): Learn about the different catalog formats supported by Lingui
- [Lingui CLI](https://lingui.dev/ref/cli.md): Learn how to set up and use Lingui CLI to extract, check, merge and compile message catalogs
- [Configuration](https://lingui.dev/ref/conf.md): Learn how to configure Lingui for your project
- [Core API Reference](https://lingui.dev/ref/core.md): The package provides the main i18n object, which manages message catalogs, active locale, and message translation and formatting
- [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md): Lingui ESLint Plugin helps you find and prevent common i18n mistakes in your code
- [Vue.js Extractor](https://lingui.dev/ref/extractor-vue.md): Extract messages from Vue single-file components with @lingui/extractor-vue. Installation, configuration and options
- [Webpack-compatible loader](https://lingui.dev/ref/loader.md): Import PO catalogs directly and compile them on the fly with @lingui/loader in Webpack, Rspack and Rsbuild, instead of running lingui compile
- [Locale Detection](https://lingui.dev/ref/locale-detector.md): Detect the user's locale with the `@lingui/detect-locale` package
- [Macros](https://lingui.dev/ref/macro.md): Transform JavaScript objects and JSX elements into ICU MessageFormat messages
- [Metro Transformer](https://lingui.dev/ref/metro-transformer.md): Use Lingui with React Native and compile your message catalogs on the fly
- [React API Reference](https://lingui.dev/ref/react.md): Reference for the Lingui React API and components
- [Solid API Reference](https://lingui.dev/ref/solid.md): Reference for the Lingui SolidJS API and components
- [SWC Plugin](https://lingui.dev/ref/swc-plugin.md): Use Lingui Macros in your SWC project
- [Vite Plugin](https://lingui.dev/ref/vite-plugin.md): Use Lingui with Vite and compile your message catalogs on the fly
- [Vue API Reference](https://lingui.dev/ref/vue.md): Reference for the Lingui Vue API, components, template macros and Vite integration
## Examples
- [Examples](https://lingui.dev/examples.md): Examples of using Lingui for internationalization (i18n) in various frameworks and libraries
## Sync & Collaboration Tools
- [Crowdin](https://lingui.dev/tools/crowdin.md): Translate a Lingui project with Crowdin. Sync PO catalogs with the Crowdin CLI or the GitHub, GitLab and Bitbucket integrations and deliver them over the air
- [Sync & Collaboration Tools](https://lingui.dev/tools/introduction.md): How to manage translations for a Lingui project. Manual catalog editing versus translation management systems, and the tools that integrate with Lingui
- [Translation.io](https://lingui.dev/tools/translation-io.md): Sync Lingui catalogs with Translation.io. Push source messages, pull translations, and give translators ICU syntax highlighting and plural management
## i18n with AI
- [i18n with AI](https://lingui.dev/ai-tools.md): Give AI coding agents accurate, up-to-date Lingui knowledge with Agent Skills, llms.txt context files, and the Context7 MCP server
## Comparisons
- [Lingui vs i18next](https://lingui.dev/misc/i18next.md): How Lingui compares with i18next and react-i18next. Message syntax, plurals, extraction tooling, catalog formats, bundle size and React Server Components
- [Lingui vs react-intl](https://lingui.dev/misc/react-intl.md): How Lingui compares with react-intl from FormatJS. Both use ICU MessageFormat, so the differences are in rich text, macros, extraction tooling and bundle size
## Optional
- [GitHub repository](https://github.com/lingui/js-lingui): Source code, issues and discussions
- [npm: @lingui/core](https://www.npmjs.com/package/@lingui/core): The runtime package; @lingui/react adds the React bindings and @lingui/cli the command line tool
- [Agent Skills](https://github.com/lingui/skills): Lingui best practices packaged as Agent Skills for coding agents
- [Context7](https://context7.com/lingui/js-lingui): The current documentation served over MCP
---
# Full Documentation Content
# i18n with AI
AI coding agents and chat tools have become an essential part of the development workflow, and internationalization is no exception. However, most AI models have limited or outdated knowledge of Lingui's APIs and best practices. This page covers the resources available to give your AI tools accurate, up-to-date Lingui knowledge so they can help you ship localized products faster.
## Agent Skills[](#agent-skills "Direct link to Agent Skills")
[Lingui Agent Skills](https://github.com/lingui/skills) are reusable, procedural knowledge packages for AI coding agents. They provide best practices, common patterns, and troubleshooting guides that agents can follow when working with Lingui - reducing hallucinations and incorrect API usage.
### Installation[](#installation "Direct link to Installation")
The skills follow the [Agent Skills format](https://agentskills.io) and work with Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot, and other compatible agents. Use whichever installer matches your tool - each one installs the whole set.
**Skills CLI:**
```
npx skills add lingui/skills
```
**Claude Code plugin** - all skills load automatically and stay up to date via `/plugin marketplace update`:
```
/plugin marketplace add lingui/skills
/plugin install lingui@lingui-skills
```
**Plugins CLI** - auto-detects your installed agent tools and installs through each one's native plugin system:
```
npx plugins add lingui/skills
```
**Gemini CLI extension:**
```
gemini extensions install https://github.com/lingui/skills
```
**GitHub CLI** (v2.90+) - installs for GitHub Copilot or any other supported agent. Use `--agent ` to target a specific tool, and `gh skill update` to pull newer versions:
```
gh skill install lingui/skills --all
```
To install a single skill instead of the full set, pass `--skill` to the Skills CLI:
```
npx skills add lingui/skills --skill lingui-best-practices
```
See the [Lingui Skills](https://github.com/lingui/skills) repository for more details about the available skills and their usage.
## Context Files[](#context-files "Direct link to Context Files")
Lingui follows the [llms.txt specification](https://llmstxt.org/) and publishes two files optimized for AI consumption: [`llms.txt`](https://lingui.dev/llms.txt), an index of the documentation pages with a short summary of each, and [`llms-full.txt`](https://lingui.dev/llms-full.txt), the full docs content in a single streamlined Markdown file. Both are regenerated with every docs build, and some AI tools auto-discover them if you provide `https://lingui.dev` as a docs source.
While these files are easy to parse, `llms-full.txt` is large and uses a lot of tokens when loaded directly into context, and a copy saved into your repository goes stale over time. They are best used as a fallback when the AI tool cannot access the latest documentation in other ways. The [Context7 MCP server](#context7-mcp) searches the same documentation on demand and returns only the relevant parts, making it the preferred option when available.
tip
Every documentation page is also available as plain Markdown: append `.md` to its URL, for example [`https://lingui.dev/ref/macro.md`](https://lingui.dev/ref/macro.md) for the Macros reference. A single page costs a fraction of the tokens of `llms-full.txt`, so when you know which part of the docs the agent needs, give it that URL instead. The links in `llms.txt` already point to these Markdown versions.
## Context7 MCP[](#context7-mcp "Direct link to Context7 MCP")
[Context7](https://context7.com/lingui/js-lingui) is an MCP (Model Context Protocol) server that provides AI tools with real-time access to up-to-date library documentation - including Lingui. Unlike static context files, Context7 indexes the latest docs and lets agents search them on demand, keeping token usage low.
### Usage[](#usage "Direct link to Usage")
Add `use context7` to any prompt and Context7-enabled agents will automatically pull relevant Lingui documentation:
```
Add i18n to my React app using Lingui. use context7
```
### MCP Server Configuration[](#mcp-server-configuration "Direct link to MCP Server Configuration")
If your AI tool supports MCP server configuration, you can add Context7 directly:
```
{
"mcpServers": {
"context7": {
"command": "npx",
"args": ["-y", "@upstash/context7-mcp"]
}
}
}
```
For tool-specific setup instructions (including remote server and other clients), visit the [Context7 page for Lingui](https://context7.com/lingui/js-lingui).
---
# Examples
To help you get started with Lingui, we've provided some example projects that demonstrate how Lingui can be integrated into various frameworks and libraries. These projects demonstrate Lingui's versatility and show you how to use it in real-world scenarios.
Check out the example projects below:
* [Vanilla JS](https://github.com/lingui/js-lingui/tree/main/examples/js)
* [Next.js App Router with SWC](https://github.com/lingui/js-lingui/tree/main/examples/nextjs-swc)
* [Next.js Pages Router with Babel](https://github.com/lingui/js-lingui/tree/main/examples/nextjs-babel)
* [React Native (uses Expo)](https://github.com/lingui/js-lingui/tree/main/examples/react-native)
* [React with Vite and Babel](https://github.com/lingui/js-lingui/tree/main/examples/vite-project-react-babel)
* [React with Vite and SWC](https://github.com/lingui/js-lingui/tree/main/examples/vite-project-react-swc)
* [Solid with Vite](https://github.com/lingui/js-lingui/tree/main/examples/vite-project-solid)
* [Vue with Vite](https://github.com/lingui/js-lingui/tree/main/examples/vite-project-vue)
* [Rspack with SWC](https://github.com/lingui/js-lingui/tree/main/examples/rspack)
* [Remix with Vite and Babel](https://github.com/lingui/js-lingui/tree/main/examples/remix-vite-babel)
* [Tanstack Start with Vite and Babel](https://github.com/lingui/js-lingui/tree/main/examples/tanstack-start)
* [React Webpack with gettext-style PO files](https://github.com/lingui/js-lingui/tree/main/examples/react-webpack-gettext)
---
# Custom Extractor
Lingui's default extractor is based on Babel and supports JavaScript (Stage 3), TypeScript, and Flow out of the box, covering most standard and modern syntax features. To extract without Babel, use the [native extractor](#native-extractor). If your project relies on experimental ECMAScript syntax or custom file formats, a custom extractor gives you the flexibility to handle these scenarios.
### Why It Doesn't Use Your Babel Config?[](#why-it-doesnt-use-your-babel-config "Direct link to Why It Doesn't Use Your Babel Config?")
Babel plugins from your configuration define transformations, and some of these may interfere with or slow down the extraction process. The extractor doesn't have to transform your code, it just analyzes it. Therefore, it's designed to understand different syntax without worrying about how the code is transpiled or down-levelled.
info
We are constantly updating the extractor to keep up with the latest ECMAScript features. However, if you find that a recently added Stage 3 feature doesn't work as expected, please [create an issue](https://github.com/lingui/js-lingui/issues/new/choose).
## Native Extractor[](#native-extractor "Direct link to Native Extractor")
[`@lingui/native-tools`](https://www.npmjs.com/package/@lingui/native-tools), the toolchain behind the [native macro transform](https://lingui.dev/ref/vite-plugin.md#native-macro-transform), also provides an SWC-based extractor for `lingui extract`. Use it to extract messages without Babel:
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/native-tools
```
```
yarn add --dev @lingui/native-tools
```
```
pnpm add --save-dev @lingui/native-tools
```
lingui.config.ts
```
import { defineConfig } from "@lingui/cli";
import { createSwcExtractor } from "@lingui/native-tools";
export default defineConfig({
// [...]
extractors: [createSwcExtractor()],
});
```
It handles `.js`, `.jsx`, `.ts`, `.tsx` files and their `.mjs`, `.cjs`, `.mts`, `.cts` variants. Macro options are read from your Lingui configuration.
Differences from the default extractor:
* [`extractorParserOptions`](https://lingui.dev/ref/conf.md#extractorparseroptions) doesn't apply. Pass SWC `parser` options instead, the same as [`jsc.parser`](https://swc.rs/docs/configuration/compilation#jscparser) in `.swcrc`. Syntax and JSX are inferred from the file name, Decorators are enabled by default.
* Flow is not supported.
note
`@lingui/cli` still depends on Babel for the default extractor and `lingui compile`, so Babel stays in your dependency tree until the next major release.
## Experimental ECMAScript Syntax[](#experimental-ecmascript-syntax "Direct link to Experimental ECMAScript Syntax")
If you are using experimental features (Stage 0 - Stage 2), you'll need to configure a custom list of parser plugins. This can be done by overriding the default extractor and using the `extractFromFileWithBabel()` function:
lingui.config.ts
```
import { extractFromFileWithBabel, defineConfig } from "@lingui/cli/api";
import type { ParserPlugin } from "@babel/parser";
export function getBabelParserOptions(filename: string) {
// https://babeljs.io/docs/en/babel-parser#latest-ecmascript-features
const parserPlugins: ParserPlugin[] = ["importAttributes", "explicitResourceManagement"];
if ([/\.ts$/, /\.mts$/, /\.cts$/, /\.tsx$/].some((r) => filename.match(r))) {
parserPlugins.push("typescript");
}
if ([/\.js$/, /\.jsx$/, /\.tsx$/].some((r) => filename.match(r))) {
parserPlugins.push("jsx");
}
return parserPlugins;
}
export default defineConfig({
// [...]
extractors: [
{
match(filename: string) {
return filename.match(/\.[cm][tj]sx?$/);
},
async extract(filename, code, onMessageExtracted, ctx) {
return extractFromFileWithBabel(filename, code, onMessageExtracted, ctx, {
// https://babeljs.io/docs/babel-parser#plugins
plugins: getBabelParserOptions(filename),
});
},
},
],
});
```
## Other Frameworks or Custom Syntax[](#other-frameworks-or-custom-syntax "Direct link to Other Frameworks or Custom Syntax")
If you're working with files that aren't valid JavaScript, you can create a custom extractor to handle them:
./my-custom-extractor.ts
```
import { extractor as defaultExtractor } from "@lingui/cli/api";
export const extractor: ExtractorType = {
match(filename: string) {
return filename.endsWith(".custom");
},
extract(filename: string, code: string, onMessageExtracted, ctx: ExtractorCtx) {
// Transform the file to plain JS + Sourcemaps
const { code: transformedCode, sourcemaps } = transformMyCustomFileToJs(filename, code);
// Access Lingui config via `ctx.linguiConfig`
// Reuse the default CLI extractor
return defaultExtractor.extract(filename, transformedCode, onMessageExtracted, {
sourcemaps,
...ctx,
});
},
};
```
### Adding the Custom Extractor to the Configuration[](#adding-the-custom-extractor-to-the-configuration "Direct link to Adding the Custom Extractor to the Configuration")
To use the custom extractor, you need to add it to your Lingui configuration file:
lingui.config.ts
```
import { extractor } from "./my-custom-extractor.ts";
import { defineConfig } from "@lingui/cli";
export default defineConfig({
// [...]
extractors: [extractor],
});
```
Important
If you are using TypeScript to create your extractor, you should use the `.ts` extension for your Lingui configuration file.
---
# Custom Formatter
If your project requires a message catalog format that Lingui doesn't [natively support](https://lingui.dev/ref/catalog-formats.md), you can create a custom formatter to handle it. A custom formatter allows you to define how extracted strings are formatted into a custom catalog format, providing flexibility for specialized workflows and integration with unique file structures.
## Overview[](#overview "Direct link to Overview")
A formatter is an object with two main functions, `parse` and `serialize`, which define how catalogs are read from and written to your custom format.
The formatter can be configured directly in your `lingui.config.{ts,js}` file - no separate package is needed:
lingui.config.{ts,js}
```
import { defineConfig } from "@lingui/cli";
import { extractor } from "./my-custom-extractor.ts";
export default defineConfig({
// [...]
format: {
catalogExtension: "json",
parse: (content: string): CatalogType => JSON.parse(content),
serialize: (catalog: CatalogType): string => JSON.stringify(catalog),
},
});
```
## Reference[](#reference "Direct link to Reference")
The shape of formatter is the following:
```
export type CatalogFormatter = {
catalogExtension: string;
/**
* Set extension used when extract to template
* Omit if the extension is the same as catalogExtension
*/
templateExtension?: string;
parse(
content: string,
ctx: { locale: string | null; sourceLocale: string; filename: string }
): Promise | CatalogType;
serialize(
catalog: CatalogType,
ctx: { locale: string | null; sourceLocale: string; filename: string; existing: string | null }
): Promise | string;
};
```
Lingui Catalog is an object with the following structure:
```
export type CatalogType = {
[msgId: string]: MessageType;
};
type CatalogExtra = Record;
export type MessageType = {
message?: string;
origin?: MessageOrigin[];
comments?: string[];
obsolete?: boolean;
context?: string;
translation?: string;
/**
* the generic field where
* formatters can store additional data
*/
extra?: Extra;
};
```
Important
If you are using TypeScript to create your formatter, you should use the `.ts` extension for your Lingui configuration file.
---
# Dynamic Loading of Message Catalogs
Internationalization in modern applications requires careful handling of localized messages to avoid bloating the initial bundle size. By default, Lingui makes it easy to load all strings for a single active locale. For even greater efficiency, developers can selectively load only the messages needed on demand using [`i18n.load`](https://lingui.dev/ref/core.md#i18n.load), ensuring minimal resource usage.
The [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) component doesn't make assumptions about your app's structure, giving you the freedom to load only the necessary messages for the currently selected language.
This guide shows how to set up dynamic loading of message catalogs, ensuring only the needed catalogs are loaded, which reduces bundle size and improves performance.
## Final i18n Loader Helper[](#final-i18n-loader-helper "Direct link to Final i18n Loader Helper")
The following code defines the complete logic for dynamically loading and activating message catalogs based on the selected locale. It ensures that only the required catalog is loaded at runtime, optimizing performance:
i18n.ts
```
import { i18n } from "@lingui/core";
export const locales = {
en: "English",
cs: "Česky",
};
export const defaultLocale = "en";
/**
* We do a dynamic import of just the catalog that we need
* @param locale any locale string
*/
export async function dynamicActivate(locale: string) {
const { messages } = await import(`./locales/${locale}/messages`);
i18n.load(locale, messages);
i18n.activate(locale);
}
```
Important
Even the "default" locale requires a catalog to be loaded. Lingui aims to keep the internationalization footprint to a minimum by dropping default messages from the production build. This way, only the catalog for the active language is loaded, avoiding duplication.
Without this optimization, switching from the default language (e.g. EN) to another (e.g. FR) would require loading both language catalogs. This strategy ensures efficiency by loading only the necessary messages for one language at a time.
### Usage in Your Application[](#usage-in-your-application "Direct link to Usage in Your Application")
To use the `dynamicActivate` function in your application, you must call it on application startup. The following example shows how to use it in a React application:
```
import React, { useEffect } from "react";
import App from "./App";
import { I18nProvider } from "@lingui/react";
import { i18n } from "@lingui/core";
import { defaultLocale, dynamicActivate } from "./i18n";
const I18nApp = () => {
useEffect(() => {
// With this method we dynamically load the catalogs
dynamicActivate(defaultLocale);
}, []);
return (
);
};
```
### Optimized Bundle Structure[](#optimized-bundle-structure "Direct link to Optimized Bundle Structure")
Looking at the contents of the build directory, we find a separate chunk for each language:
```
i18n-0.c433b3bd.chunk.js
i18n-1.f0cf2e3d.chunk.js
main.ab4626ef.js
```
When the page is first loaded, only the main bundle and the bundle for the first language are loaded:

After changing the language in the UI, the second language bundle is loaded:

## Dependency Tree Extractor (experimental)[](#dependency-tree-extractor-experimental "Direct link to Dependency Tree Extractor (experimental)")
The Dependency Tree Extractor is an experimental feature designed to improve message extraction by analyzing the dependency tree of your application. This tool improves the efficiency of loading localized messages by identifying only the necessary messages for each component or page, rather than extracting all messages into a single catalog.
This allows for a more granular extraction process, resulting in smaller and more relevant message catalogs.
For detailed guidance on message extraction, refer to the [Message Extraction](https://lingui.dev/guides/message-extraction.md) guide.
---
# Explicit vs Generated IDs
When internationalizing your application, you may need to decide whether to use explicit or generated IDs for your messages.
In this guide, we explore the basic concepts of explicit and generated IDs, and then delve into a comprehensive comparison, highlighting the advantages and disadvantages of each approach.
## Differences Between Explicit and Generated IDs[](#differences-between-explicit-and-generated-ids "Direct link to Differences Between Explicit and Generated IDs")
### Explicit ID[](#explicit-id "Direct link to Explicit ID")
An explicit ID, often referred to as a user-defined or custom ID, is a manually assigned identifier associated with a specific message. These IDs are typically chosen by developers and are explicitly specified within your code. The typical explicit ID may look like `index.header.title` or `modal.buttons.cancel`.
Example:
```
Lingui example
// extracted as
{
id: "index.header.title",
message: "Lingui example",
}
```
### Generated IDs[](#generated-ids "Direct link to Generated IDs")
On the other hand, generated IDs are created automatically by the internationalization library. In Lingui, such IDs are created based on the source message and [context](#context).
Example:
```
Lingui example
// extracted as
{
id: "MbT6FE",
message: "Lingui example",
}
```
### Benefits of Generated IDs[](#benefits-of-generated-ids "Direct link to Benefits of Generated IDs")
* **Avoiding the "naming things" problem:** you don't need to come up with a name for each single phrase in the app. Lingui generates the IDs (in the form of short hashes) from the messages.
* **Better developer experience:** developers can focus on coding without needing to manually assign IDs, leading to a more streamlined development process. Searching for a user-facing string will lead to the place in code where it's used, as opposed to taking you to a (typically JSON) file full of translations.
* **Avoiding duplicates:** duplicate messages are merged together automatically. Translators will not have to translate the same phrases again and again. This could lead to cost savings, especially if translators charge by word count.
* **Smaller bundle:** Lingui generates short IDs such as `MbT6FE` which are typically shorter than manually crafted IDs like `index.header.title`. This results in a smaller bundle size, optimizing your application's performance.
* **Preventing ID collisions:** as your application scales, explicit IDs can potentially lead to conflicts. Lingui's generated IDs help avoid such collisions.
* **Readability is a non-issue:** even though generated IDs aren't human-readable, you would hardly see them. Translators work with the source string in the catalog, while the IDs remain behind the scenes.
### Benefits of Explicit IDs[](#benefits-of-explicit-ids "Direct link to Benefits of Explicit IDs")
* **Control:** developers have full control over the naming and assignment of explicit IDs. This control allows for precise targeting and easy maintenance of internationalization keys.
* **Loose coupling:** explicit IDs are loosely coupled with the messages (as opposed to when they are generated from the messages). This means that if the message changes, the ID remains the same. When your team uses a TMS (Translation Management System), this makes it easier even for non-technical people to update the strings.
* **Readability:** explicit IDs often have meaningful names, making it easier for developers, translators, and content creators to understand their purpose within the codebase.
* **Predictability:** since explicit IDs are manually assigned, they remain stable across different versions of your application, reducing the likelihood of breaking changes during updates.
tip
If you use explicit IDs, you can opt in to [Typed Message IDs](https://lingui.dev/guides/typed-message-ids.md) for autocomplete and compile-time validation of your message identifiers.
The choice between these two strategies depends on your project requirements and priorities. However, it's important to note that Lingui provides the full range of benefits, especially with generated IDs.
## Context[](#context "Direct link to Context")
By default, when using generated IDs, the same text elements are extracted with the same ID, and then translated once. However, this might not always be desirable since the same text can have different meanings and translations. For example, consider the word "right" and its two possible meanings:
* correct as in "you are right"
* direction as in "turn right"
To distinguish these two cases, you can add `context` to messages. The same text elements with different contexts are extracted with different IDs. Then, they can be translated differently and merged back into the application as different translation entries.
Regardless of whether you use generated IDs or not, adding context makes the translation process less challenging and helps translators interpret the source accurately. You, in return, get translations of better quality faster and decrease the number of context-related issues you would need to solve. See [Translator-friendly Messages](https://lingui.dev/guides/translator-friendly-messages.md) for the other ways to give translators context.
Examples:
```
import { Trans } from "@lingui/react/macro";
right;
right;
// ↓ ↓ ↓ ↓ ↓ ↓
import { Trans } from "@lingui/react";
;
;
```
or with non-JSX macro:
```
import { msg } from "@lingui/core/macro";
const ex1 = msg({
message: `right`,
context: "direction",
});
const ex2 = msg({
message: `right`,
context: "correctness",
});
// ↓ ↓ ↓ ↓ ↓ ↓
import { msg } from "@lingui/core/macro";
const ex1 = {
id: "d1wX4r",
message: `right`,
};
const ex2 = {
id: "16eaSK",
message: `right`,
};
```
## Using Generated IDs[](#using-generated-ids "Direct link to Using Generated IDs")
### With JSX Macro[](#with-jsx-macro "Direct link to With JSX Macro")
```
import { Trans } from "@lingui/react/macro";
function render() {
return (
<>
>
);
}
```
In the example code above, the content of [`Trans`](https://lingui.dev/ref/macro.md#trans) is transformed into a message in MessageFormat syntax. By default, this message is used for generating the ID. Considering the example above, the catalog would contain these entries:
```
const catalog = [
{
id: "MbT6FE",
message: "Lingui example",
},
{
id: "9_omjw",
message: "Hello <0>{name}0>.",
},
];
```
### With Core Macro[](#with-core-macro "Direct link to With Core Macro")
In the following example, the message `Hello World` will be extracted and used to create an ID:
```
import { msg } from "@lingui/core/macro";
msg`Hello World`;
```
tip
Enforce generated IDs with the Lingui [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md) rule [`require-implicit-id`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/require-implicit-id.md).
## Using Explicit IDs[](#using-explicit-ids "Direct link to Using Explicit IDs")
### With JSX Macro[](#with-jsx-macro-1 "Direct link to With JSX Macro")
To use custom IDs in JSX macros, pass the ID as a prop to the component:
```
import { Trans } from "@lingui/react/macro";
function render() {
return (
<>
>
);
}
```
The messages with IDs `msg.header` and `msg.hello` will be extracted with their default values as `Lingui example` and `Hello <0>{name}0>.` respectively.
### With Core Macro[](#with-core-macro-1 "Direct link to With Core Macro")
To use custom IDs in non-JSX macros, call the [`msg`](https://lingui.dev/ref/macro.md#definemessage) function with a message descriptor object, passing the ID using the `id` property:
```
import { msg } from "@lingui/core/macro";
msg({ id: "msg.greeting", message: `Hello World` });
```
Message `msg.greeting` will be extracted with default value `Hello World`.
For all other js macros ([`plural`](https://lingui.dev/ref/macro.md#plural), [`select`](https://lingui.dev/ref/macro.md#select), [`selectOrdinal`](https://lingui.dev/ref/macro.md#selectordinal), use them inside [`msg`](https://lingui.dev/ref/macro.md#definemessage) macro to pass ID (in this case, `'msg.caption'`).
```
import { msg, plural } from "@lingui/core/macro";
msg({
id: "msg.caption",
message: plural(count, {
one: "# image caption",
other: "# image captions",
}),
});
```
tip
Enforce explicit IDs with the Lingui [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md) rule [`require-explicit-id`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/require-explicit-id.md).
## See Also[](#see-also "Direct link to See Also")
* [Message Extraction](https://lingui.dev/guides/message-extraction.md)
* [Macros Reference](https://lingui.dev/ref/macro.md)
---
# Lazy Translations
Lazy translation allows you to defer translation of a message until it's rendered, giving you flexibility in how and where you define messages in your code. With lazy translation, you can tag a string with the [`msg`](https://lingui.dev/ref/macro.md#definemessage) macro to create a *message descriptor* that can be saved, passed around as a variable, and rendered later.
## Usage Example[](#usage-example "Direct link to Usage Example")
To render the message descriptor as a string-only translation, pass it to the [`i18n.t()`](https://lingui.dev/ref/core.md#i18n.t) method:
```
import { msg } from "@lingui/core/macro";
import { i18n } from "@lingui/core";
const favoriteColors = [msg`Red`, msg`Orange`, msg`Yellow`, msg`Green`];
export function getTranslatedColorNames() {
return favoriteColors.map((color) => i18n.t(color));
}
```
## Usage in React[](#usage-in-react "Direct link to Usage in React")
To render the message descriptor in a React component, pass its `id` to the [`Trans`](https://lingui.dev/ref/react.md#trans) component as a value of the `id` prop:
```
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react";
const favoriteColors = [msg`Red`, msg`Orange`, msg`Yellow`, msg`Green`];
export default function ColorList() {
return (
{favoriteColors.map((color) => (
))}
);
}
```
Important
Please note that we import the `` component from `@lingui/react` to use the runtime version, as the message is already defined and we don't need the compile-time macro here.
### Picking a Message Based on a Variable[](#picking-a-message-based-on-a-variable "Direct link to Picking a Message Based on a Variable")
Sometimes you need to choose between different messages to display depending on the value of a variable. For example, imagine you have a numeric "status" code that comes from an API, and you need to display a message that represents the current status.
An easy way to do this is to create an object that maps the possible values of "status" to message descriptors (tagged with the [`msg`](https://lingui.dev/ref/macro.md#definemessage) macro) and render them as needed with deferred translation:
```
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
const statusMessages = {
["STATUS_OPEN"]: msg`Open`,
["STATUS_CLOSED"]: msg`Closed`,
["STATUS_CANCELLED"]: msg`Cancelled`,
["STATUS_COMPLETED"]: msg`Completed`,
};
export default function StatusDisplay({ statusCode }) {
const { _ } = useLingui();
return
{_(statusMessages[statusCode])}
;
}
```
### Memoization Pitfall[](#memoization-pitfall "Direct link to Memoization Pitfall")
In the following contrived example, we document how a welcome message will or will not be updated when locale changes. The documented behavior may not be intuitive at first, but it is expected, because of the way the `useMemo` dependencies work.
To avoid bugs with stale translations, use the `t` function returned from the [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macro: it is safe to use with memoization because its reference changes whenever the Lingui context updates.
Keep in mind that `useMemo` is primarily a performance optimization tool in React. Because of this, there might be no need to memoize your translations. Additionally, this issue is not present when using the `Trans` component, which we recommend using whenever possible.
```
import { i18n } from "@lingui/core";
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
const welcomeMessage = msg`Welcome!`;
// ❌ Bad! This code won't work
export function Welcome() {
const buggyWelcome = useMemo(() => {
return i18n.t(welcomeMessage);
}, []);
return
{buggyWelcome}
;
}
// ❌ Bad! This code won't work either because the reference to i18n does not change
export function Welcome() {
const { i18n } = useLingui();
const buggyWelcome = useMemo(() => {
return i18n.t(welcomeMessage);
}, [i18n]);
return
{buggyWelcome}
;
}
// ✅ Good! `useMemo` consumes the `t` function from the `useLingui` macro
export function Welcome() {
const { t } = useLingui();
const welcome = useMemo(() => {
return t(welcomeMessage);
}, [t]);
return
{/*
Plurals are managed using ICU plural rules.
Nesting of i18n components is allowed.
Syntactically valid message in ICU MessageFormat is guaranteed.
*/}
Only one user is using this library!
}
other={
{numUsers} users are using this library!
}
/>
);
}
```
## See Also[](#see-also "Direct link to See Also")
* [Installation and Setup](https://lingui.dev/installation.md)
* [i18n with AI](https://lingui.dev/ai-tools.md)
---
# Lingui vs i18next
[i18next](https://www.i18next.com/) is one of the most widely used internationalization frameworks for JavaScript, with bindings for React, Vue, Angular, Svelte and many other frameworks and platforms. Both libraries solve the same problem, but they start from different ideas. With i18next you invent a key for each string, put the text in a JSON file and look the key up at runtime. With Lingui you write the text where it is displayed, the IDs are generated from it and the catalogs are compiled at build time.
That difference runs through everything else on this page: how messages are written, what translators receive and what ships to the browser.
## At a Glance[](#at-a-glance "Direct link to At a Glance")
| | Lingui | i18next |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| Writing messages | The text stays in the code: `` t`Hello ${name}` ``. The catalog is generated from it | You choose a key, add the text to a JSON file and reference the key: `t("greeting", { name })` |
| Message IDs | Generated from the source text, so there is nothing to name and duplicates merge on their own. Explicit IDs when you want them | Keys you define and keep unique yourself. Natural-language keys are possible with `keySeparator: false` |
| Message syntax | ICU MessageFormat. Placeholders, plurals and selects stay inside one message | Own `{{name}}` syntax. Each plural form is a separate key (`key_one`, `key_other`). ICU needs the `i18next-icu` plugin |
| Extraction | Built in. `lingui extract` finds every message, merges it into all catalogs and marks removed ones obsolete | Separate tools: `i18next-cli` (the successor of `i18next-parser`) or `i18next-scanner` |
| Translator context | Source locations, comments and context travel with each message in the PO file | JSON has no comments. Key locations need a custom `i18next-cli` metadata plugin |
| Catalog format | PO by default, which every translation tool opens. JSON, CSV and custom formatters available | JSON, bundled inline or loaded through backend plugins. YAML and JSON5 via `i18next-cli` |
| Runtime | Catalogs are compiled at build time and no message parser ships. Core about 2 kB gzipped | Messages interpolated at runtime. Core about 14 kB gzipped |
| React | `@lingui/react` with macros. React Server Components through `@lingui/react/server` | `react-i18next`. For React Server Components, `next-i18next` v16 adds `getT` and `useT`, or you create an i18next instance per request |
| Other frameworks | React Native, Vue, SolidJS, Astro, Svelte, Node.js | Vue, Angular, Svelte, SolidJS, Astro, Remix, Node.js and more |
| TypeScript | Written in TypeScript. Opt-in typed message IDs via module augmentation | Ships type definitions. Typed keys and interpolation values via `CustomTypeOptions` |
Bundle sizes were measured with [bundlejs](https://bundlejs.com/) in September 2026 for `@lingui/core` 6.6 and `i18next` 26.4.
## Basic Comparison[](#basic-comparison "Direct link to Basic Comparison")
Here's a simple example of how to use i18next:
```
import i18next from "i18next";
i18next.init({
lng: "en",
resources: {
en: {
translation: {
key: "Hello world",
},
},
},
});
```
```
import i18next from "i18next";
document.getElementById("output").innerHTML = i18next.t("key");
```
To know what this line renders, you open the JSON file and look up `key`. The equivalent example with Lingui keeps the text in the code, and the CLI generates the catalog from it:
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
export default defineConfig({
sourceLocale: "en",
locales: ["en", "cs", "fr"],
catalogs: [
{
path: "/src/locales/{locale}/messages",
include: ["src"],
},
],
});
```
```
import { t } from "@lingui/core/macro";
document.getElementById("output").innerHTML = t`Hello world`;
```
tip
This example uses a macro for the translation. Macros are a powerful feature of Lingui that allows you to write messages directly in your code. Read more about [Macros](https://lingui.dev/ref/macro.md).
If you prefer to define explicit IDs for your messages, you can follow this approach:
```
import { t } from "@lingui/core/macro";
document.getElementById("output").innerHTML = t({ id: "msg.greeting", message: `Hello World` });
```
Read more about [Explicit vs Generated Message IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md).
## Interpolation[](#interpolation "Direct link to Interpolation")
Interpolation is a key internationalization (i18n) feature that allows you to insert dynamic values into your translations. Both Lingui and i18next support interpolation.
i18next sample:
```
import i18next from "i18next";
i18next.t("My name is {{name}}", { name: "Tom" });
i18next.t("msg.name", { name: "Tom" });
```
Lingui sample:
```
import { t } from "@lingui/core/macro";
const name = "Tom";
t`My name is ${name}`;
t({ id: "msg.name", message: `My name is ${name}` });
```
Lingui names the placeholder after the variable, so the message and the code cannot drift apart. With i18next, the `{{name}}` in the JSON file and the `{ name }` in the call are matched by hand.
## Formatting[](#formatting "Direct link to Formatting")
Both Lingui and i18next formatting functions are based on the [Intl API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl).
### Numbers[](#numbers "Direct link to Numbers")
i18next sample:
```
import i18next from "i18next";
i18next.t("intlNumber", { val: 1000 });
// --> Some 1,000
i18next.t("intlNumber", { val: 1000.1, minimumFractionDigits: 3 });
// --> Some 1,000.100
i18next.t("intlNumber", { val: 1000.1, formatParams: { val: { minimumFractionDigits: 3 } } });
// --> Some 1,000.100
i18next.t("intlNumberWithOptions", { val: 2000 });
// --> Some 2,000.00
i18next.t("intlNumberWithOptions", { val: 2000, minimumFractionDigits: 3 });
// --> Some 2,000.000
```
Lingui sample:
```
import { i18n } from "@lingui/core";
i18n.activate("en");
new Intl.NumberFormat(i18n.locale).format(12345.678);
// Returns "12,345.678"
new Intl.NumberFormat(i18n.locale, { style: "currency", currency: "USD" }).format(12345.678);
// Returns "$12,345.68"
i18n.activate("cs");
new Intl.NumberFormat(i18n.locale).format(12345.678);
// Returns "12 345,678"
new Intl.NumberFormat(i18n.locale, { style: "currency", currency: "CZK" }).format(12345.678);
// Returns "12 345,68 Kč"
```
### DateTime[](#datetime "Direct link to DateTime")
i18next sample:
```
import i18next from "i18next";
i18next.t("intlDateTime", { val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)) });
// --> On the 12/20/2012
i18next.t("intlDateTime", {
val: new Date(Date.UTC(2012, 11, 20, 3, 0, 0)),
formatParams: {
val: { weekday: "long", year: "numeric", month: "long", day: "numeric" },
},
});
// --> On the Thursday, December 20, 2012
```
Lingui sample:
```
import { i18n } from "@lingui/core";
const d = new Date("2021-07-23T16:23:00");
i18n.activate("en");
new Intl.DateTimeFormat(i18n.locale).format(d);
// Returns "7/23/2021"
new Intl.DateTimeFormat(i18n.locale, { timeStyle: "medium" }).format(d);
// Returns "4:23:00 PM"
new Intl.DateTimeFormat(i18n.locale, { dateStyle: "medium", timeStyle: "medium" }).format(d);
// Returns "Jul 23, 2021, 4:23:00 PM"
```
## Plurals[](#plurals "Direct link to Plurals")
Lingui uses the [ICU MessageFormat](https://lingui.dev/guides/message-format.md) syntax to handle plurals. All forms of a message stay together in one string that the translator sees as a whole.
For example:
```
plural(numBooks, {
one: "# book",
other: "# books",
});
```
Under the hood, the [`plural`](https://lingui.dev/ref/macro.md#plural) macro is replaced with a low-level [`i18n._`](https://lingui.dev/ref/core.md#i18n._) call. In production, the example will look like this:
```
i18n._({
id: "d1wX4r",
// stripped on production
// message: '{numBooks, plural, one {# book} other {# books}}',
values: { numBooks },
});
```
When we extract messages from the source code using the [Lingui CLI](https://lingui.dev/ref/cli.md), we get:
```
{numBooks, plural, one {# book} other {# books}}
```
i18next stores each plural form under its own key. The suffixes follow the CLDR plural categories returned by `Intl.PluralRules`, so English uses `_one` and `_other`, while Arabic adds `_zero`, `_two`, `_few` and `_many`:
```
{
"key_one": "item",
"key_other": "items"
}
```
```
import i18next from "i18next";
i18next.t("key", { count: 0 }); // -> "items"
i18next.t("key", { count: 1 }); // -> "item"
i18next.t("key", { count: 5 }); // -> "items"
```
In the catalog, `item` and `items` are two separate entries. Nothing ties them together or shows the translator the sentence they appear in. If you prefer ICU plurals with i18next, the [`i18next-icu`](https://github.com/i18next/i18next-icu) plugin switches the message syntax to ICU MessageFormat, at which point i18next's own interpolation and plural keys no longer apply.
## Context[](#context "Direct link to Context")
By providing context, you can differentiate translations for the same sentences or provide translators with more details. Both i18next and Lingui have the context feature to differentiate messages.
i18next sample:
```
import i18next from "i18next";
i18next.t("Right", { context: "direction" });
```
Lingui sample:
```
import { msg } from "@lingui/core/macro";
msg({
message: "Right",
context: "direction",
});
```
tip
Lingui also writes the source locations of each message into the `.po` file, together with `msgctxt` when a context is given, so translators can see where a message is used:
en.po
```
#: src/App.js:5
msgctxt "direction"
msgid "Right"
msgstr "Right"
```
JSON has no comment syntax, so this information is not part of i18next catalogs by default. `i18next-cli` can record key locations through a custom metadata plugin.
## React Integration[](#react-integration "Direct link to React Integration")
Both libraries provide React components for handling translations in React applications. Lingui provides a set of [React Macros](https://lingui.dev/ref/macro.md#react-macros) that simplify writing messages directly in your code. i18next provides a `Trans` component to handle translations in JSX.
i18next sample:
```
import { Trans } from "react-i18next";
const HelloWorld = () => {
return Hello World!;
};
```
The translation lives under `welcome` in the JSON file. The children are the fallback when the key is missing.
Lingui sample:
```
import { Trans } from "@lingui/react/macro";
const HelloWorld = () => {
return Hello World!;
};
```
Here the children are the message. The ID is derived from them, and `lingui extract` writes the entry to the catalog.
## Summary[](#summary "Direct link to Summary")
Both libraries build on the same foundations: the `Intl` API for formatting, CLDR plural rules and one catalog per locale. They differ in how much of the bookkeeping is yours.
**Lingui:**
* Messages are written in the source with macros. There are no keys to invent and no JSON file to keep in sync, because `lingui extract` generates the catalog from the code.
* Plurals, selects and rich text stay inside one message, and React elements inside a message stay in one translatable string.
* Catalogs are PO files by default, which every translation tool opens and which carry source locations and comments for translators. JSON, CSV and [custom formatters](https://lingui.dev/guides/custom-formatter.md) are available. See [Catalog Formats](https://lingui.dev/ref/catalog-formats.md).
* Catalogs are compiled ahead of time, so the runtime ships without a message parser and stays around 2 kB gzipped.
* Works with vanilla JS, React (including React Server Components), React Native, Next.js, Vue, SolidJS, Astro, Svelte and Node.js.
**i18next:**
* Messages are looked up by key. Resources are plain JSON and can be loaded from the filesystem, over HTTP or from a translation platform through backend plugins.
* Has been around for more than a decade and covers nearly every i18n scenario, with an official CLI for extraction, type generation and linting.
* Has a large plugin ecosystem: language detectors, backends, post processors and alternative message formats such as ICU and Fluent.
* Has bindings or ports for many frameworks and platforms, including Vue, Angular, Svelte, .NET, Go, iOS and Android.
i18next's breadth is real, and if your organization already runs it across several stacks, that continuity counts. For a JavaScript or TypeScript codebase, Lingui covers the same ground with less to maintain by hand: no keys to name, no JSON to keep in sync, and catalogs that open in any translation tool.
---
# Lingui vs react-intl
[react-intl](https://formatjs.github.io/docs/react-intl/) is the React binding of [FormatJS](https://formatjs.github.io/), a long-standing i18n project that also ships a Vue binding, a CLI and `Intl` polyfills. [Lingui](https://github.com/lingui/js-lingui) is a close relative: both libraries use ICU MessageFormat for messages, and their low-level APIs look almost the same. The differences are in how much of the message syntax you write yourself, how much the tooling does for you, and what ships to the browser.
## At a Glance[](#at-a-glance "Direct link to At a Glance")
| | Lingui | react-intl (FormatJS) |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Writing messages | Macros generate the ICU message from JSX or a template literal: `Hello {name}` | You write the ICU string yourself: `` |
| Rich text | Components inside a message are plain JSX. The translator sees `Read the <0>documentation0>` | Each tag maps to a render function in `values`: `link: (chunks) => {chunks}` |
| Message IDs | Generated from the source text by the macro, explicit IDs optional | Explicit `id`, or a generated hash with the Babel or SWC plugin or the TypeScript transformer |
| Extraction | `lingui extract` merges new messages into every locale's catalog, keeps existing translations and marks removed ones obsolete | `formatjs extract` writes the source messages to one JSON file. Translated files are handled separately, with formatters for Crowdin, Lokalise, Smartling and Transifex |
| Catalog format | PO by default, which every translation tool opens. JSON, CSV and custom formatters available | JSON, in the FormatJS layout or a translation platform's layout |
| Runtime | Catalogs are compiled at build time and no parser ships. Core and React bindings about 4 kB gzipped | Messages parsed at runtime unless pre-compiled with `formatjs compile --ast`. About 15 kB gzipped |
| Server Components | `@lingui/react/server`. `Trans` works in server and client components alike | `react-intl/server` with `createIntl`. `FormattedMessage` and `useIntl` are client-only |
| Beyond React | `@lingui/core` for Node.js and plain JS, `@lingui/solid` for SolidJS. The same core and CLI serve React Native, Vue, Astro and Svelte | `@formatjs/intl` for plain JS, `vue-intl` for Vue |
| TypeScript | Written in TypeScript. Opt-in typed message IDs via module augmentation | Written in TypeScript. Typed message IDs via the `FormatjsIntl` global namespace |
Bundle sizes were measured with [bundlejs](https://bundlejs.com/) in September 2026 for `@lingui/core` and `@lingui/react` 6.6 and `react-intl` 10.1, with `react` excluded.
## Basic Comparison[](#basic-comparison "Direct link to Basic Comparison")
Here's an example from the react-intl docs:
```
{name}, unreadCount }}
/>
```
Looking at the low-level API of Lingui, there isn't much difference:
```
{name}, unreadCount }}
/>
```
There's really no reason to reinvent the wheel when both libs are built on top of the same message syntax. The story doesn't end here, though.
## Translations with Rich-Text Markup[](#translations-with-rich-text-markup "Direct link to Translations with Rich-Text Markup")
Suppose we have the following text:
```
```
In react-intl, this would be translated as:
```
{chunks},
}}
/>
```
Each tag needs a function that receives the translated chunks and wraps them.
Lingui extends the ICU MessageFormat with tags. The above example would be:
```
}} />
```
The element is passed as it is, with no wrapper function, and the translator gets the message in one piece: `Read the documentation`.
## Macros for Component-Based Message Syntax[](#macros-for-component-based-message-syntax "Direct link to Macros for Component-Based Message Syntax")
Lingui provides powerful [Macros](https://lingui.dev/ref/macro.md) that automatically generate a message syntax.
Let's go back to the previous example:
```
```
The macro will then parse the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro children and automatically generate `message` and `components` props in the form described in the previous section.
This is very useful when adding i18n to an existing project. All we need to do is wrap all messages in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro.
Let's compare it to the react-intl solution to see the difference:
```
```
FormatJS also has Babel and SWC plugins, but they generate message IDs and pre-compile messages. The ICU string in `defaultMessage` is still written by hand.
note
It's also worth mentioning that the message IDs are completely optional. Lingui is unopinionated in this way and perfectly works with messages as IDs as well:
```
```
The message ID is `Read the <0>documentation0>.` instead of `msg.docs`. Both solutions have pros and cons and the library lets you choose the one which works best for you.
Read more about [Explicit vs Generated Message IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md).
## Plurals[](#plurals "Direct link to Plurals")
Another very common linguistic feature is pluralization.
Let's take a look at the original example from react-intl docs:
```
{name}, unreadCount }}
/>
```
Using Lingui macros, we could combine [`Trans`](https://lingui.dev/ref/macro.md#trans) and [`Plural`](https://lingui.dev/ref/macro.md#plural-1) components:
```
Hello {name}, you have {unreadCount}
```
and the final message would be very similar:
```
{name}0>, you have {unreadCount, number} {unreadCount, plural,
one {message}
other {messages}
}`}
values={{ name, unreadCount }}
/>
```
The only difference is the `<0>` tag in the message, since Lingui can handle components in variables as well as in the message itself.
note
It's worth mentioning here that this is not the best example of using plurals. Make your translators happy by moving plurals to the top of the message:
```
Hello {name}, you have {unreadMessages} message.
>
}
other={
<>
Hello {name}, you have {unreadMessages} messages.
>
}
/>
```
Even though both variants are syntactically valid in ICU MessageFormat, the second one is easier for translating, because (again) the translator gets the phrase in one piece.
## Text Attributes[](#text-attributes "Direct link to Text Attributes")
Components can't be used in some contexts, e.g. to translate text attributes. react-intl provides `formatMessage` from the `useIntl` hook for this. Lingui provides the `t` macro, which the [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macro binds to the `i18n` instance from the React context:
```
import { useLingui } from "@lingui/react/macro";
import { plural } from "@lingui/core/macro";
function Flag({ name, count }) {
const { t } = useLingui();
return (
<>
{name}
>
);
}
```
Custom IDs are supported as well:
```
{name}
```
## External Message Catalog[](#external-message-catalog "Direct link to External Message Catalog")
Let's say our application has been internationalized and we want to send the messages to the translator.
FormatJS ships a CLI: `formatjs extract` collects the source messages into a single JSON file, and `formatjs compile` turns the translated files you get back into the format react-intl consumes, verifying the ICU syntax on the way. Formatters for Crowdin, Lokalise, Smartling and Transifex are built in. Keeping the translated files in step with the source, and noticing which translations are stale, happens outside the CLI, usually in the translation platform.
Lingui's [CLI](https://lingui.dev/ref/cli.md) closes that loop itself. `lingui extract` merges new messages into every locale's catalog, keeps the existing translations and marks removed messages as obsolete, so each PO file always mirrors the current source and stale entries are visible at a glance. It supports both the Babel and SWC ecosystems for extracting messages.
## Compiling Messages[](#compiling-messages "Direct link to Compiling Messages")
Parsing and formatting ICU messages is the largest part of an i18n runtime. Lingui compiles each message at build time into a small structure that the runtime fills with values, so neither a parser nor a MessageFormat compiler ships to the browser. This is what `lingui compile` does by default, with nothing to opt into. Plural rules come from `Intl.PluralRules`, so there is no locale data to load by hand.
react-intl parses messages at runtime by default. The FormatJS CLI can pre-compile messages to an AST with `formatjs compile --ast`, and pairing that with the parser-free build of `@formatjs/icu-messageformat-parser` cuts the bundle by about 40% according to the FormatJS docs. The formatter itself stays in the bundle.
## Summary[](#summary "Direct link to Summary")
Both libraries use ICU MessageFormat and have similar low-level APIs, so porting from one to the other is mostly mechanical. What differs is how much of the work the library takes off your hands.
**Lingui:**
* Macros generate the message syntax from JSX and template literals. Rich text is written as plain JSX, and there is no ICU string to hand-write or keep in step with the code.
* Extraction and compilation are part of the core toolchain, and the CLI keeps every locale's catalog in step with the source. Catalogs are PO files by default, with JSON, CSV and custom formats available.
* Catalogs are compiled ahead of time. Core and React bindings together stay around 4 kB gzipped.
* The same core serves vanilla JS, Node.js, React Native, Vue, SolidJS, Astro and Svelte.
**react-intl:**
* Is one of the longest-standing i18n libraries for React, used in many production websites.
* Is part of FormatJS, whose `@formatjs/intl` core also powers `vue-intl` and whose polyfills fill gaps in the `Intl` API.
* Has lots of resources available online.
Because the message syntax is shared, an existing react-intl codebase can move to Lingui without rewriting its messages. Each `FormattedMessage` becomes a `Trans` with the same message, and from then on the ICU string is generated for you.
---
# Catalog Formats
Catalog format (configured by the [`format`](https://lingui.dev/ref/conf.md#format) option) refers to the offline catalog file format. This format is never used in production, because the catalog is compiled into a JS module.
The reason for this build step is that the choice of catalog format depends on the individual internationalization workflow. On the other hand, the runtime catalog should be as simple as possible so that it can be parsed quickly without additional overhead.
## PO[](#po "Direct link to PO")
PO files are translation files used by [gettext](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html) internationalization system. This is the **recommended** and the **default** catalog format in Lingui.
[](https://www.npmjs.com/package/@lingui/format-po) [](https://www.npmjs.com/package/@lingui/format-po)
The advantages of this format are:
* readable even for large messages
* supports comments for translators
* supports metadata (origin, flags)
* supports contexts
* standard format supported by many localization tools
### Installation[](#po-installation "Direct link to Installation")
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/format-po
```
```
yarn add --dev @lingui/format-po
```
```
pnpm add --save-dev @lingui/format-po
```
### Usage[](#po-usage "Direct link to Usage")
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-po";
export default defineConfig({
// [...]
format: formatter({ lineNumbers: false }),
});
```
### Configuration[](#po-configuration "Direct link to Configuration")
PO formatter accepts the following options:
| Option | Type | Default | Description |
| ----------------------------- | ------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `origins` | boolean | `true` | Include comments in the PO file that indicate where each message is used in the source code. This provides additional context during the translation |
| `lineNumbers` | boolean | `true` | Include line numbers in the origin comments. This makes it easier to locate messages in the source code |
| `printLinguiId` | boolean | `false` | Add a `js-lingui-id: hash` comment to each message in the PO file. This ID is a hash generated by Lingui |
| `explicitIdAsDefault` | boolean | `false` | Use the `msgid` as is for messages with explicit IDs. The formatter will add the `js-lingui-explicit-id` flag for such strings |
| `customHeaderAttributes` | `{[key: string]: string}` | `{}` | Allows adding custom key-value pairs to the PO file header |
| `printPlaceholdersInComments` | boolean \| `{ limit?: number }` | `true` | Print values for unnamed placeholders as comments for each message. This can give translators more context for better translations. By default, the first 3 placeholders are displayed |
| `foldLength` | number | `0` | Maximum line width before folding long strings. When a string exceeds this length, it will be split across multiple lines. Set to `0` to disable folding (strings will only break on actual newlines) |
| `compactMultiline` | boolean | `true` | When `true`, multiline strings start with content on the first line. When `false`, uses GNU gettext's traditional format with an empty first line. The compact format is recommended as it's compatible with translation platforms that may strip empty first lines |
### Examples[](#po-examples "Direct link to Examples")
```
#: src/App.js:3
#. Comment for translators
msgid "messageId"
msgstr "Translated Message"
#: src/App.js:3
#, obsolete
msgid "obsoleteId"
msgstr "Obsolete Message"
```
Messages with context are exported in the following way:
```
#: src/Inbox.js:12
msgctxt "my context"
msgid "msg.inbox"
msgstr "Message Inbox"
```
Messages with plurals are exported in [ICU MessageFormat](https://lingui.dev/guides/message-format.md):
```
msgid "{count, plural, one {Message} other {Messages}}"
msgstr "{count, plural, one {Message} other {Messages}}"
```
Messages with placeholders:
```
t`Hello ${user.name} ${value}`;
```
are exported as:
```
#. placeholder {0}: user.name
msgid "Hello {0} {value}"
msgstr "Hello {0} {value}"
```
## PO with gettext Plurals[](#po-gettext "Direct link to PO with gettext Plurals")
When using localization backends that don't understand the ICU plural syntax exported by the default `po` formatter, **po-gettext** can be used to read and write to PO files using gettext-native plurals.
[](https://www.npmjs.com/package/@lingui/format-po-gettext) [](https://www.npmjs.com/package/@lingui/format-po-gettext)
### Installation[](#po-gettext-installation "Direct link to Installation")
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/format-po-gettext
```
```
yarn add --dev @lingui/format-po-gettext
```
```
pnpm add --save-dev @lingui/format-po-gettext
```
### Usage[](#po-gettext-usage "Direct link to Usage")
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-po-gettext";
export default defineConfig({
// [...]
format: formatter({ lineNumbers: false }),
});
```
### Configuration[](#po-gettext-configuration "Direct link to Configuration")
The PO Gettext formatter accepts the following options:
| Option | Type | Default | Description |
| ---------------------- | ------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `origins` | boolean | `true` | Include comments in the PO file that indicate where each message is used in the source code. This provides additional context during the translation |
| `lineNumbers` | boolean | `true` | Include line numbers in the origin comments. This makes it easier to locate messages in the source code |
| `disableSelectWarning` | boolean | `false` | Disable warnings about unsupported `Select` features encountered in catalogs. This can be useful if you're aware of the limitation and want to suppress related warnings |
| `customICUPrefix` | string | `"js-lingui:"` | Override the default prefix for ICU and plural comments in the final PO catalog |
| `mergePlurals` | boolean | `false` | Combine plural entries that have the same content but different variables into a single PO entry |
| `foldLength` | number | `0` | Maximum line width before folding long strings. When a string exceeds this length, it will be split across multiple lines. Set to `0` to disable folding |
| `compactMultiline` | boolean | `true` | When `true`, multiline strings start with content on the first line. When `false`, uses GNU gettext's traditional format with an empty first line |
### Examples[](#po-gettext-examples "Direct link to Examples")
With this format, plural messages are exported in the following ways, depending on whether an explicit ID is set:
* Message **with custom ID "my\_message"** that is pluralized on property "*someCount*".
```
#. js-lingui:pluralize_on=someCount
msgid "my_message"
msgid_plural "my_message_plural"
msgstr[0] "Singular case"
msgstr[1] "Case number {someCount}"
```
Note that `msgid_plural` was created by appending a `_plural` suffix.
* Message **without custom ID** that is pluralized on property "*anotherCount*".
To allow matching this PO item to the appropriate catalog entry when deserializing, the original ICU message is also stored in the generated comment.
```
#. js-lingui:icu=%7BanotherCount%2C+plural%2C+one+%7BSingular+case%7D+other+%7BCase+number+%7BanotherCount%7D%7D%7D&pluralize_on=anotherCount
msgid "Singular case"
msgid_plural "Case number {anotherCount}"
msgstr[0] "Singular case"
msgstr[1] "Case number {anotherCount}"
```
Note how `msgid` and `msgid_plural` were extracted from the original message.
* Message **with a custom comment prefix**.
Some TMS might modify the ICU comment by attempting to split lines to be 80 characters or less, or have trouble reading lingui comments because of the `js-lingui:` prefix. To change the prefix, set `customICUPrefix` to modify the prefix for ICU comments.
```
# with default prefix
#. js-
#. lingui:icu=%7BanotherCount%2C+plural%2C+one+%7BSingular+case%7D+other+%7BCase+number+%7BanotherCount%7D%7D%7D&pluralize_on=anotherCount
# customICUPrefix = jsi18n:
#. jsi18n:icu=%7BanotherCount%2C+plural%2C+one+%7BSingular+case%7D+other+%7BCase+number+%7BanotherCount%7D%7D%7D&pluralize_on=anotherCount
```
#### Duplicate Plurals[](#duplicate-plurals "Direct link to Duplicate Plurals")
When two calls to `plural` or `` are made with identical strings, but pluralize on different variables, they will create separate PO entries. However, `msgid` will be the same. Some TMS might not allow duplicate `msgid`, even with different comments, and should use `mergePlurals` option to merge these entries into a single PO entry during extraction. During compilation, it will be re-expanded to multiple units.
```
plural(count, {
one: "one book",
other: "many books",
});
plural(anotherCount, {
one: "one book",
other: "many books",
});
```
Without `mergePlurals`:
```
#. js-lingui:icu={count, plural, one {one book} other {many books}}&pluralize_on=count
msgid "one book"
msgid_plural "many books"
msgstr[0] "one book"
msgstr[1] "many books"
#. js-lingui:icu={anotherCount, plural, one {one book} other {many books}}&pluralize_on=anotherCount
msgid "one book"
msgid_plural "many books"
msgstr[0] "one book"
msgstr[1] "many books"
```
With `mergePlurals`:
```
#. js-lingui:icu={$var, plural, one {one book} other {many books}}&pluralize_on=count,anotherCount
msgid "one book"
msgid_plural "many books"
msgstr[0] "one book"
msgstr[1] "many books"
```
### Limitations[](#po-gettext-limitations "Direct link to Limitations")
This format comes with several caveats and should only be used when using ICU plurals in PO files is not an option:
* Nested/multiple plurals in a message as shown in [`plural`](https://lingui.dev/ref/macro.md#plural) are not supported because they cannot be expressed with gettext plurals. Messages containing nested/multiple formats will not be output correctly.
* A [`Plural`](https://lingui.dev/ref/macro.md#plural-1) nested inside a [`Trans`](https://lingui.dev/ref/macro.md#trans) (`You have `) is exported as a single ICU message rather than as `msgid`/`msgid_plural`. Keep the plural as the top-level translation unit; the [`no-plural-inside-trans`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-plural-inside-trans.md) ESLint rule catches this.
* The [`select`](https://lingui.dev/ref/macro.md#select) and [`selectOrdinal`](https://lingui.dev/ref/macro.md#selectordinal) cannot be expressed with gettext plurals, but the original ICU format is still stored in the `msgid`/`msgstr` properties. To disable the warning that this may not be the expected behavior, add `{ disableSelectWarning: true }` to the [`format`](https://lingui.dev/ref/conf.md#format) options.
* Source/development languages with more than two plurals could experience difficulties when no custom IDs are used, as gettext cannot have more than two plurals cases identifying an item (`msgid` and `msgid_plural`).
* Gettext doesn't support plurals for negative and fractional numbers even though some languages have special rules for these cases.
## JSON[](#json "Direct link to JSON")
This format is used to store messages in a JSON file. There are two types of JSON format: [minimal](#minimal-style) and [lingui](#lingui-style).
[](https://www.npmjs.com/package/@lingui/format-json) [](https://www.npmjs.com/package/@lingui/format-json)
### Installation[](#json-installation "Direct link to Installation")
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/format-json
```
```
yarn add --dev @lingui/format-json
```
```
pnpm add --save-dev @lingui/format-json
```
### Usage[](#json-usage "Direct link to Usage")
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-json";
export default defineConfig({
// [...]
format: formatter({ style: "lingui" }),
});
```
### Configuration[](#json-configuration "Direct link to Configuration")
JSON formatter accepts the following options:
| Option | Type | Default | Description |
| ------------- | ------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `style` | `"lingui"` \| `"minimal"` | `"lingui"` | Specify the output style of the JSON file. `lingui` includes full Lingui-specific metadata, while `minimal` may output a more compact format |
| `origins` | boolean | `true` | Include information in the JSON file about where each message is used in the source code. This provides additional context during the translation |
| `lineNumbers` | boolean | `true` | Include line numbers in the origin comments. This makes it easier to locate messages in the source code |
| `indentation` | number | `2` | Set the number of spaces to use for indentation in the output JSON file. This affects the readability of the file when opened in a text editor |
### Examples[](#json-examples "Direct link to Examples")
#### Minimal style[](#minimal-style "Direct link to Minimal style")
A simple JSON file where each key is a message ID and the value is the translation. The JSON is flat, and there's no reason to use nested keys. The usual motivation behind nested JSON is to save file space, but this file format is only used offline.
The downside of this format is that all metadata about the message is lost. This includes the default message, the origin of the message, and any message flags (obsolete, fuzzy, etc.).
```
{
"messageId": "translation"
}
```
#### Lingui style[](#lingui-style "Direct link to Lingui style")
This file format simply outputs all internal data in JSON format. It's the original file format used by Lingui before support for other catalog formats was added. It might be useful for tools build on top of Lingui CLI which needs to further process catalog data.
```
{
"messageId": {
"translation": "Translated message",
"message": "Default message",
"description": "Comment for translators",
"origin": [["src/App.js", 3]]
},
"obsoleteId": {
"translation": "Obsolete message",
"origin": [["src/App.js", 3]],
"obsolete": true
}
}
```
## CSV[](#csv "Direct link to CSV")
The CSV format is a simple format that can be used to import and export messages from spreadsheets or other tools that support CSV files. It has two columns: message ID and message (source or translation).
[](https://www.npmjs.com/package/@lingui/format-csv) [](https://www.npmjs.com/package/@lingui/format-csv)
### Installation[](#csv-installation "Direct link to Installation")
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/format-csv
```
```
yarn add --dev @lingui/format-csv
```
```
pnpm add --save-dev @lingui/format-csv
```
### Usage[](#csv-usage "Direct link to Usage")
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-csv";
export default defineConfig({
// [...]
format: formatter(),
});
```
This formatter has no configurable options.
### Examples[](#csv-examples "Direct link to Examples")
```
messageId,Message
msg.common,String for translation
```
## See Also[](#see-also "Direct link to See Also")
* [Custom Formatter](https://lingui.dev/guides/custom-formatter.md)
---
# Lingui CLI
The `@lingui/cli` tool provides the `lingui` command which allows you to extract messages from source files into message catalogs, check them, and compile these catalogs for production use.
## Installation[](#installation "Direct link to Installation")
1. Install `@lingui/cli` as a development dependency:
* npm
* Yarn
* pnpm
```
npm install --save-dev @lingui/cli
```
```
yarn add --dev @lingui/cli
```
```
pnpm add --save-dev @lingui/cli
```
2. Add the following scripts to your `package.json`:
package.json
```
{
"scripts": {
"extract": "lingui extract",
"compile": "lingui compile"
}
}
```
tip
If you use TypeScript, you can add the `--typescript` flag to the `compile` script to produce compiled message catalogs with TypeScript types:
package.json
```
{
"scripts": {
"compile": "lingui compile --typescript"
}
}
```
## Global Options[](#global-options "Direct link to Global Options")
### `--config `[](#--config-config "Direct link to --config-config")
Path to the configuration file. If not set, the default file is loaded as described in the [Configuration](https://lingui.dev/ref/conf.md) reference.
## Commands[](#commands "Direct link to Commands")
### `extract`[](#extract "Direct link to extract")
```
lingui extract [files...]
[--clean]
[--overwrite]
[--format ]
[--locale ]
[--convert-from ]
[--verbose]
[--watch [--debounce ]]
[--workers ]
```
The `extract` command scans source files to locate and extract messages, generating separate message catalogs for each language.
This process involves:
1. Extracting messages from files based on the `include` and `exclude` settings in the [`catalogs`](https://lingui.dev/ref/conf.md#catalogs) section of the configuration file.
2. Merging the newly extracted messages with any existing message catalogs.
3. Updating and saving the message catalogs.
4. Printing extraction statistics for each language, including the total number of messages and any missing translations.
tip
Refer to the [Message Extraction](https://lingui.dev/guides/message-extraction.md) guide to learn more about this process and the options available.
#### `files`[](#extract-files "Direct link to extract-files")
Filter source paths to extract messages only from specific files. For example:
```
lingui extract src/components
```
This command extracts messages from files within the `src/components/**/*` path. You can also pass multiple paths for extraction.
This feature is useful when you want to extract messages from files that are staged for commit. For example, you can use husky to automatically extract messages from staged files before committing:
package.json
```
{
"husky": {
"hooks": {
"pre-commit": "lingui extract $(git diff --name-only --staged)"
}
}
}
```
#### `--clean`[](#extract-clean "Direct link to extract-clean")
By default, the extract command merges messages extracted from source files with existing message catalogs, ensuring that translated messages are preserved and not accidentally lost.
However, over time, some messages may be removed from the source code. You can use the following option to clean up your message catalogs and remove obsolete messages.
#### `--overwrite`[](#extract-overwrite "Direct link to extract-overwrite")
Update translations for [`sourceLocale`](https://lingui.dev/ref/conf.md#sourcelocale) from source.
#### `--format `[](#extract-format "Direct link to extract-format")
Extract message catalogs to the specified file format (see the [`format`](https://lingui.dev/ref/conf.md#format) option for more details).
#### `--locale `[](#extract-locale "Direct link to extract-locale")
Extract data for the specified locales only.
#### `--convert-from `[](#extract-convert-from "Direct link to extract-convert-from")
Convert message catalogs from the previous format (see the [`format`](https://lingui.dev/ref/conf.md#format) option for more details).
#### `--verbose`[](#extract-verbose "Direct link to extract-verbose")
Print additional information.
#### `--watch`[](#extract-watch "Direct link to extract-watch")
Enable watch mode to monitor changes in files located in the paths specified in the configuration file or in the command itself. Note that this feature is intended for development use only, as it does not remove obsolete translations.
#### `--debounce `[](#extract-debounce "Direct link to extract-debounce")
Delay the extraction by `` milliseconds, bundling multiple file changes together.
#### `--workers`[](#extract-workers "Direct link to extract-workers")
Number of worker threads to use (default: CPU count - 1, capped at 8; on 1-2 core machines, all cores). Pass `--workers 1` to disable worker threads and run everything in a single process
Worker threads can significantly improve performance on large projects. However, on small projects they may provide little benefit or even be slightly slower due to thread startup overhead.
A larger worker pool also increases memory usage. Adjust this value for your project to achieve the best performance.
### `extract-template`[](#extract-template "Direct link to extract-template")
```
lingui extract-template [--verbose]
```
This command extracts messages from your source files and generates a `.pot` template file. Any artifacts created by this command can be safely ignored in version control.
If your message catalogs are not synchronized with the source and some messages are missing, the application will fallback to the template file. Running this command before building the application is recommended to ensure all messages are accounted for.
#### `--verbose`[](#extract-template-verbose "Direct link to extract-template-verbose")
Print additional information.
### `compile`[](#compile "Direct link to compile")
```
lingui compile
[--strict]
[--format ]
[--verbose]
[--typescript]
[--namespace ]
[--watch [--debounce ]]
[--workers ]
[--output-prefix ]
```
Once you have all the catalogs ready and translated, you can use this command to compile all the catalogs into minified JS/TS files. It compiles message catalogs located in the [`path`](https://lingui.dev/ref/conf.md#catalogs) directory and generates minified JavaScript files. The resulting file is a string that is parsed into a plain JS object using `JSON.parse`.
The output looks like this:
```
export const messages = JSON.parse(`{
// object with keys (translation ids) and values (translations)
}`);
```
Messages added to the compiled file are collected in a specific order:
1. Translated messages from the specified locale.
2. Translated messages from the fallback locale for the specified locale.
3. Translated message from default fallback locale.
4. Message key.
It is also possible to merge the translated catalogs into a single file per locale by specifying [`catalogsMergePath`](https://lingui.dev/ref/conf.md#catalogsmergepath) in the configuration.
tip
The compiled files can be safely ignored by your version control system, since these files must be created each time you deploy to production. We recommend you to create the compiled catalogs in CI as part of your deployment process. Always remember to **use compiled catalogs** in deployments.
.gitignore
```
your_locale_folder/**/*.js
```
#### `--overwrite`[](#compile-overwrite "Direct link to compile-overwrite")
Overwrite source locale translations from source.
#### `--strict`[](#compile-strict "Direct link to compile-strict")
Fail if the compiled catalog still has missing translations after `fallbackLocales` are applied, or if message compilation produces errors.
This preserves the default validation behavior used by Lingui 6. The compiled output uses the normal fallback resolution behavior regardless of strict mode, although catalogs for locales that fail strict validation may not be emitted.
#### `--format `[](#compile-format "Direct link to compile-format")
Format of message catalogs (see the [`format`](https://lingui.dev/ref/conf.md#format) option for more details).
#### `--verbose`[](#compile-verbose "Direct link to compile-verbose")
Print additional information.
#### `--namespace`[](#compile-namespace "Direct link to compile-namespace")
Specify the namespace for compiled message catalogs (see also [`compileNamespace`](https://lingui.dev/ref/conf.md#compilenamespace) for global configuration).
#### `--typescript`[](#compile-typescript "Direct link to compile-typescript")
Is the same as using [`compileNamespace`](https://lingui.dev/ref/conf.md#compilenamespace) with the value "ts". Generates a `{compiledFile}.ts` file and the exported object is typed using TS.
#### `--watch`[](#compile-watch "Direct link to compile-watch")
Watch mode. Watches only for changes in locale files in your defined locale catalogs. For example, `locales\en\messages.po`.
#### `--debounce `[](#compile-debounce "Direct link to compile-debounce")
Delays compilation by `` milliseconds to avoid multiple compilations for subsequent file changes.
#### `--workers`[](#compile-workers "Direct link to compile-workers")
Number of worker threads to use (default: CPU count - 1, capped at 8; on 1-2 core machines, all cores). Pass `--workers 1` to disable worker threads and run everything in a single process
Worker threads can significantly improve performance on large projects. However, on small projects they may provide little benefit or even be slightly slower due to thread startup overhead.
A larger worker pool also increases memory usage. Adjust this value for your project to achieve the best performance.
#### `--output-prefix `[](#compile-output-prefix "Direct link to compile-output-prefix")
Adds a custom string to the beginning of compiled message catalogs (a header/prefix). By default, Lingui adds `/*eslint-disable*/` to prevent linters from reporting issues in generated files.
Use this option for other tools that rely on header directives (e.g., different linters, coverage tools, or formatters). Provide the full prefix exactly as it should appear in the output.
**Default value:** `/*eslint-disable*/`
**Examples:**
```
# For Oxlint
lingui compile --output-prefix "/*oxlint-disable*/"
# For Biome
lingui compile --output-prefix "/*biome-ignore lint: auto-generated*/"
# For no prefix at all
lingui compile --output-prefix ""
```
The generated file header will look like:
```
/*your-prefix-here*/ export const messages = JSON.parse("{}");
```
### `check`[](#check "Direct link to check")
```
lingui check
```
The `check` command is a namespace for validation subcommands. Running `lingui check` without a subcommand prints help and exits without running any validation.
These subcommands are useful in CI when you want to fail fast on stale catalogs or missing translations but do not need compilation artifacts yet.
#### `sync`[](#sync "Direct link to sync")
```
lingui check sync
[--locale ]
[--clean]
[--overwrite]
[--verbose]
[--workers ]
```
Checks whether locale catalogs are synchronized with the current source code. It fails if the expected catalog differs from the existing catalog.
This validation checks locale catalogs only. It does not validate `.pot` / template freshness.
#### `missing`[](#missing "Direct link to missing")
```
lingui check missing
[--locale ]
[--mode ]
[--verbose]
[--workers ]
```
Checks whether locale catalogs have missing translations. By default, this validation uses `resolved` mode, which matches `lingui compile --strict`: translations are considered missing only if they are still missing after `fallbackLocales` are applied.
Use `--mode catalog` to fail when the target locale catalog itself has missing translations before `fallbackLocales` are applied. This command performs validation without compiling catalogs.
#### `sync --locale `[](#check-sync-locale "Direct link to check-sync-locale")
Only check the specified locales when running `lingui check sync`.
#### `sync --clean`[](#check-sync-clean "Direct link to check-sync-clean")
Before comparing catalogs, remove obsolete messages from the expected catalog. Existing obsolete messages are still reported as out of sync.
#### `sync --overwrite`[](#check-sync-overwrite "Direct link to check-sync-overwrite")
When running the `sync` validation, mirror `lingui extract --overwrite`. Source locale translations are expected to be overwritten from source messages.
#### `sync --verbose`[](#check-sync-verbose "Direct link to check-sync-verbose")
Print detailed findings for each failing `sync` validation.
#### `sync --workers`[](#check-sync-workers "Direct link to check-sync-workers")
Number of worker threads to use (default: CPU count - 1, capped at 8; on 1-2 core machines, all cores). Pass `--workers 1` to disable worker threads and run everything in a single process
#### `missing --locale `[](#check-missing-locale "Direct link to check-missing-locale")
Only check the specified locales when running `lingui check missing`.
#### `missing --mode `[](#check-missing-mode "Direct link to check-missing-mode")
Controls how missing translations are detected when running `lingui check missing`.
* `resolved` (default): fail only if a translation is still missing after `fallbackLocales` are applied.
* `catalog`: fail if the target locale catalog itself has missing translations before `fallbackLocales` are applied.
#### `missing --verbose`[](#check-missing-verbose "Direct link to check-missing-verbose")
Print detailed findings for each failing `missing` validation.
#### `missing --workers`[](#check-missing-workers "Direct link to check-missing-workers")
Number of worker threads to use (default: CPU count - 1, capped at 8; on 1-2 core machines, all cores). Pass `--workers 1` to disable worker threads and run everything in a single process
## Configuring the Source Locale[](#configuring-the-source-locale "Direct link to Configuring the Source Locale")
One limitation of checking for missing translations is that the English message catalog typically does not require translations since our source code is in English. This issue can be resolved by configuring the [`sourceLocale`](https://lingui.dev/ref/conf.md#sourcelocale) in the configuration file.
## Compiling Catalogs in CI[](#compiling-catalogs-in-ci "Direct link to Compiling Catalogs in CI")
If you're using CI, it's a good idea to add the `compile` command to your build process. Alternatively, you can also use a [Webpack loader](https://lingui.dev/ref/loader.md), [Vite plugin](https://lingui.dev/ref/vite-plugin.md) or [Metro transformer](https://lingui.dev/ref/metro-transformer.md).
Depending on your localization setup, you might also want to run the `extract` command in CI and upload the extracted messages to a [translation service](https://lingui.dev/tools/introduction.md).
## See Also[](#see-also "Direct link to See Also")
* [Lingui Configuration](https://lingui.dev/ref/conf.md)
* [Message Extraction](https://lingui.dev/guides/message-extraction.md)
* [Catalog Formats](https://lingui.dev/ref/catalog-formats.md)
* [Custom Extractor](https://lingui.dev/guides/custom-extractor.md)
---
# Configuration
The following reference covers all supported configuration options in Lingui. To learn more about configuring Lingui, read the [Installation and Setup](https://lingui.dev/installation.md) guide.
By default, Lingui looks for the configuration in the following locations:
* `lingui.config.js` or `lingui.config.ts` file exporting a configuration object (recommended).
You can also define the environment variable `LINGUI_CONFIG` with the path to your config file.
In the case of TypeScript-based config you can use ESM format and *export default*.
## catalogs[](#catalogs "Direct link to catalogs")
Default value:
```
[
{
path: "/locale/{locale}/messages",
include: [""],
exclude: ["**/node_modules/**"],
},
];
```
The `catalogs` configuration defines the location of message catalogs and specifies which files are included when the [`extract`](https://lingui.dev/ref/cli.md#extract) command scans for messages.
* `path`: the directory where the message catalogs are located. It should not end with a slash and must not include a file extension, which depends on the [`format`](#format) configuration. The `{locale}` token will be replaced by the catalog's locale.
* `include` and `exclude`: these patterns specify which files to include or exclude during the extraction process. They are passed to [minimatch](https://github.com/isaacs/minimatch) for pattern matching.
* [``](#rootdir): represents the root directory of the project. It is replaced with the actual root directory when the configuration is loaded. By default, [``](#rootdir) represents the configuration file's location.
The `path`, `include`, and `exclude` patterns are interpreted relative to the current process CWD (current working directory).
The `{name}` token in the `path` will be replaced with the catalog name. Be sure to include the `{name}` pattern in the source path as well, as it acts like a `*` glob pattern:
```
{
"catalogs": [
{
"path": "/components/{name}/locale/{locale}",
"include": ["/components/{name}/"]
}
]
}
```
#### Examples[](#examples "Direct link to Examples")
Let's assume we use `locales: ["en", "cs"]` and `format: "po"` in all examples.
#### All catalogs in one directory[](#all-catalogs-in-one-directory "Direct link to All catalogs in one directory")
```
{
"catalogs": [
{
"path": "locales/{locale}"
}
]
}
```
```
locales/
├── en.po
└── cs.po
```
#### Catalogs in separate directories[](#catalogs-in-separate-directories "Direct link to Catalogs in separate directories")
```
{
catalogs: [
{
path: "locales/{locale}/messages",
},
];
}
```
```
locales
├── en/
│ └── messages.po
└── cs/
└── messages.po
```
#### Separate catalogs per component, placed inside component directory[](#separate-catalogs-per-component-placed-inside-component-directory "Direct link to Separate catalogs per component, placed inside component directory")
```
{
"catalogs": [
{
"path": "components/{name}/locale/{locale}",
"include": ["components/{name}/"]
}
]
}
```
```
components/
├── RegistrationForm/
│ ├── locale/
│ │ ├── en.po
│ │ └── cs.po
│ ├── RegistrationForm.test.js
│ └── RegistrationForm.js
└── LoginForm/
├── locale/
│ ├── en.po
│ └── cs.po
├── LoginForm.test.js
└── LoginForm.js
```
#### Separate catalogs per component, placed inside shared directory[](#separate-catalogs-per-component-placed-inside-shared-directory "Direct link to Separate catalogs per component, placed inside shared directory")
```
{
"catalogs": [
{
"path": "locale/{locale}/{name}",
"include": ["components/{name}/"]
}
]
}
```
```
.
├── locale/
│ ├── en/
│ │ ├── RegistrationForm.po
│ │ └── LoginForm.po
│ └── cs/
│ ├── RegistrationForm.po
│ └── LoginForm.po
└── components/
├── RegistrationForm/
│ ├── RegistrationForm.test.js
│ └── RegistrationForm.js
└── LoginForm/
├── LoginForm.test.js
└── LoginForm.js
```
## locales[](#locales "Direct link to locales")
Default value: `[]`
The locale tags used in the project. The [`extract`](https://lingui.dev/ref/cli.md#extract) and [`compile`](https://lingui.dev/ref/cli.md#compile) commands write a catalog for each locale specified. Each locale should be a valid [BCP-47 code](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html):
```
{
"locales": ["en", "cs"]
}
```
## fallbackLocales[](#fallbacklocales "Direct link to fallbackLocales")
Default value: `{}`
Translations from `fallbackLocales` are used if the translation for the given locale is missing. It uses [CLDR Parent Locales](https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/parentLocales.json) by default, unless you override it with a `false` to use the default message or message ID instead:
```
{
"fallbackLocales": false
}
```
The `fallbackLocales` object allows to configure fallback locales for each locale instance:
```
{
"fallbackLocales": {
"en-US": ["en-GB", "en"],
"es-MX": "es"
}
}
```
In this example, if any translation isn't found on `en-US`, then it will search on `en-GB`, after that if not found we'll search in `en`.
it's also possible to configure a `default` fallback locale for all locales:
```
{
"fallbackLocales": {
"en-US": ["en-GB", "en"],
"es-MX": "es",
"default": "en"
}
}
```
## sourceLocale[](#sourcelocale "Direct link to sourceLocale")
Default value: `""`
`sourceLocale` specifies the default language of message IDs in your source files. The catalog for `sourceLocale` doesn't need actual translations since message IDs are used as-is by default. However, you can still override any message ID by providing a custom translation.
The main difference between `sourceLocale` and [`fallbackLocales`](#fallbacklocales) is their purpose: `sourceLocale` defines the language used for message IDs, while `fallbackLocales` provides alternative translations when specific messages are missing for a particular locale.
## pseudoLocale[](#pseudolocale "Direct link to pseudoLocale")
Default value: `""`
Locale used for pseudolocalization. For example, when you set `pseudoLocale: "en"`, all messages in the `en` catalog will be pseudo-localized. The locale must be included in the `locales` config.
It can be provided as a string (deprecated), an object to additionally configure the underlying [`pseudolocale`](https://github.com/MartinCerny-awin/pseudolocale) library, or an array of objects to define multiple pseudolocales with different parameters. The token delimiter is managed internally by Lingui (to keep HTML tags, ICU macros and variables intact) and therefore cannot be configured.
caution
The string form (`pseudoLocale: "pseudo"`) is deprecated and will be removed in a future major release. Use the object form (`pseudoLocale: { locale: "pseudo" }`) or an array of objects instead.
| Option | Type | Default | Description |
| ----------------- | --------- | ----------- | --------------------------------------------------------------------------------------------------- |
| `locale` | `string` | — | Locale used for pseudolocalization (required in the object form) |
| `prepend` | `string` | `""` | String prepended to the beginning of every pseudo-localized message |
| `append` | `string` | `""` | String appended to the end of every pseudo-localized message |
| `extend` | `number` | `0` | Extends the width of the string by the given percentage (e.g. `0.3` adds 30%) |
| `extendCharacter` | `string` | `" "` | Character used to pad messages when `extend` is set |
| `override` | `string` | `undefined` | Replaces every (non-token) character with the given one. Handy to quickly spot untranslated strings |
| `rightToLeft` | `boolean` | `false` | Emulates right-to-left languages by inserting Unicode RTL override marks |
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
// Simple form
export default defineConfig({
locales: ["en", "pseudo"],
sourceLocale: "en",
pseudoLocale: "pseudo",
catalogs: [],
});
// Extended form
export default defineConfig({
locales: ["en", "pseudo"],
sourceLocale: "en",
pseudoLocale: {
locale: "pseudo",
prepend: "⟦ ",
append: " ⟧",
extend: 0.4,
extendCharacter: ".",
},
catalogs: [],
});
// Multiple pseudolocales
export default defineConfig({
locales: ["en", "pseudo-en", "pseudo-ar"],
sourceLocale: "en",
pseudoLocale: [
{ locale: "pseudo-en", prepend: "⟦ ", append: " ⟧", extend: 0.4 },
{ locale: "pseudo-ar", rightToLeft: true },
],
catalogs: [],
});
```
Read more about [Pseudolocalization](https://lingui.dev/guides/pseudolocalization.md).
## catalogsMergePath[](#catalogsmergepath "Direct link to catalogsMergePath")
Default value: `""`
Define the path where translated catalogs are merged into a single file per locale during the [`compile`](https://lingui.dev/ref/cli.md#compile) process.
#### Example[](#example "Direct link to Example")
Let's assume we have [separate catalogs per component, placed inside shared directory](#separate-catalogs-per-component-placed-inside-shared-directory).
Using the `catalogsMergePath`, separate catalogs can be merged into a single file:
```
{
"catalogs": [
{
"path": "/locale/{locale}/{name}",
"include": ["components/{name}/"]
}
],
+ "catalogsMergePath": "locales/{locale}"
}
```
```
.
├── locale/
│ ├── en/
│ │ ├── RegistrationForm.po
- │ │ ├── RegistrationForm.js
│ │ ├── LoginForm.po
- │ │ └── LoginForm.js
│ └── cs/
│ ├── RegistrationForm.po
- │ ├── RegistrationForm.js
│ ├── LoginForm.po
- │ └── LoginForm.js
+ ├── locales/
+ │ ├── en.js
+ │ └── cs.js
└── components/
├── RegistrationForm/
│ ├── RegistrationForm.test.js
│ └── RegistrationForm.js
└── LoginForm/
├── LoginForm.test.js
└── LoginForm.js
```
## compileNamespace[](#compilenamespace "Direct link to compileNamespace")
Default value: `cjs`
Specify namespace for exporting compiled messages. See [`compile`](https://lingui.dev/ref/cli.md#compile) command.
#### cjs[](#cjs "Direct link to cjs")
Use CommonJS exports:
```
/* eslint-disable */module.exports={messages: {"..."}}
```
#### es[](#es "Direct link to es")
Use ES6 named export:
```
/* eslint-disable */export const messages = {"..."}
```
#### ts[](#ts "Direct link to ts")
Use ES6 named export + `.ts` file with an additional `{compiledFile}.d.ts` file:
```
/* eslint-disable */export const messages = {"..."}
```
```
import { Messages } from "@lingui/core";
declare const messages: Messages;
export { messages };
```
#### json[](#json "Direct link to json")
```
{"messages": {"..."}}
```
#### (window|global).(.\*)[](#windowglobal "Direct link to (window|global).(.*)")
Assign compiled messages to `window` or `global` object. Specify an identifier after `window` or `global` to which the catalog is assigned, e.g. `window.i18n`.
For example, setting [`compileNamespace`](#compilenamespace) to `window.i18n` creates file similar to this:
```
/* eslint-disable */window.i18n={messages: {"..."}}
```
## extractorParserOptions[](#extractorparseroptions "Direct link to extractorParserOptions")
note
This option is deprecated. If you want to change parser options, pass it directly to extractor implementation
```
import { createBabelExtractor } from "@lingui/cli/api/extractors/babel";
export default {
// [...]
extractors: [createBabelExtractor({ parserOptions: { tsExperimentalDecorators: true } })],
};
```
Specify additional options used to parse source files when extracting messages.
```
{
"extractorParserOptions": {
"tsExperimentalDecorators": false,
"flow": false
}
}
```
#### tsExperimentalDecorators[](#tsexperimentaldecorators "Direct link to tsExperimentalDecorators")
Default value: `false`
By default, standard decorators (Stage3) are applied to TS files. Enable this if you want to use TypeScript's experimental decorators.
#### flow[](#flow "Direct link to flow")
Default value: `false`
Lingui does not ship with [Flow](https://flow.org/) typing. However, you can use Lingui in projects written in Flow. Enable this option to tell the extractor that your sources use Flow syntax.
## compilerBabelOptions[](#compilerbabeloptions "Direct link to compilerBabelOptions")
Default value:
```
{
"minified": true,
"jsescOption": {
"minimal": true
}
}
```
Specify extra babel options used to generate files when messages are being compiled. We use internally `@babel/generator` that accepts some configuration for generating code with/out ASCII characters. These are all the options available: [jsesc](https://github.com/mathiasbynens/jsesc).
```
{
"compilerBabelOptions": {
"jsescOption": {
"minimal": false
}
}
}
```
This example configuration will compile with escaped ASCII characters ([jsesc#minimal](https://github.com/mathiasbynens/jsesc#minimal)).
## format[](#format "Direct link to format")
Default value: `po`
Message catalog format. The `po` formatter is used by default. Other formatters are available as separate packages.
lingui.config.{js,ts}
```
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-po";
export default defineConfig({
// [...]
format: formatter({ lineNumbers: false }),
});
```
Read more about available formatters in [Catalog Formats](https://lingui.dev/ref/catalog-formats.md) or create your own [Custom Formatter](https://lingui.dev/guides/custom-formatter.md).
## orderBy[](#orderby "Direct link to orderBy")
Default value: `message`
Order of messages in catalog:
#### message[](#message "Direct link to message")
Sort by source message.
#### messageId[](#messageid "Direct link to messageId")
Sort by the message ID, `js-lingui-id` will be used if no custom id provided.
#### origin[](#origin "Direct link to origin")
Sort by message origin (e.g. `App.js:3`)
#### Custom Function[](#custom-function "Direct link to Custom Function")
You can provide custom sort function:
```
export default defineConfig({
// [...]
orderBy: (a, b) => {
/* `a` and `b` has a shape
* {
* messageId: string
* entry: ExtractedMessageType
* }
*/
const aIsGlobal = a.messageId.startsWith("global.");
const bIsGlobal = b.messageId.startsWith("global.");
// Put `global.*` entries first
if (aIsGlobal && !bIsGlobal) return -1;
if (!aIsGlobal && bIsGlobal) return 1;
// Otherwise, sort alphabetically
return a.messageId.localeCompare(b.messageId);
},
});
```
## rootDir[](#rootdir "Direct link to rootDir")
Default: The root of the directory containing your Lingui configuration file or the `package.json`.
This is the directory where the Lingui CLI scans for messages in your source files during the extraction process.
Note that using `` as a string token in any other path-based config settings will refer back to this value.
## runtimeConfigModule[](#runtimeconfigmodule "Direct link to runtimeConfigModule")
Default value: `["@lingui/core", "i18n"]`
This setting specifies the module path for the exported `i18n` object. The first value in the array is the module path, and the second is the name of the import. This configuration is essential for [macros](https://lingui.dev/ref/macro.md) that need to reference the global `i18n` object.
You only need to set this value if you use custom object created using [`setupI18n`](https://lingui.dev/ref/core.md#setupi18n):
For example, if you have a custom module that exports the `i18n` object:
```
import { i18n } from "./custom-i18n-config";
```
```
{
"runtimeConfigModule": ["./custom-i18n-config", "i18n"]
}
```
You may use a different named export:
```
import { myI18n } from "./custom-i18n-config";
```
```
{
"runtimeConfigModule": ["./custom-i18n-config", "myI18n"]
}
```
In more advanced scenarios, you may need to change the module from which the [`Trans`](https://lingui.dev/ref/macro.md#trans) or [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macros are imported:
```
import { Trans, useLingui } from "./custom-config";
```
```
{
"runtimeConfigModule": {
"Trans": ["./custom-config", "Trans"],
"useLingui": ["./custom-config", "useLingui"]
}
}
```
## extractors[](#extractors "Direct link to extractors")
Default value: `[babel]`
Extractors it's the way to customize which extractor you want for your codebase.
```
{
"extractors": [
myCustomExtractor,
]
}
```
See the [Custom Extractor](https://lingui.dev/guides/custom-extractor.md) guide for instructions on creating your own extractor, or use the [native extractor](https://lingui.dev/guides/custom-extractor.md#native-extractor) to extract without Babel.
## macro.corePackage[](#macrocorepackage "Direct link to macro.corePackage")
Default value: `["@lingui/macro", "@lingui/core/macro"]`
Allows customizing the Core Macro package name that the Lingui macro detects.
```
// lingui.config
{
macro: {
corePackage: ["@lingui/myMacro"],
}
}
// app.tsx
import { msg } from "@lingui/myMacro";
msg`Hello`; // <-- would be correctly picked up by macro
```
This setting mostly useful for external framework integrations.
## macro.jsxPackage[](#macrojsxpackage "Direct link to macro.jsxPackage")
Default value: `["@lingui/macro", "@lingui/react/macro"]`
Allows customizing the JSX Macro package name that the Lingui macro detects.
```
// lingui.config
{
macro: {
jsxPackage: ["@lingui/myMacro"],
}
}
// app.tsx
import { Trans } from "@lingui/myMacro";
Hello; // <-- would be correctly picked up by macro
```
This setting mostly useful for external framework integrations.
## macro.jsxPlaceholderAttribute[](#macrojsxplaceholderattribute "Direct link to macro.jsxPlaceholderAttribute")
Default value: `undefined`
The JSX attribute name used to assign explicit placeholder names to JSX elements inside ``. When set, the macro reads this attribute from JSX elements to use as the placeholder name in the message string, and strips the attribute from the output.
```
// lingui.config
{
macro: {
jsxPlaceholderAttribute: "_t",
}
}
// source
Click here;
// extracted message: "Click here"
```
Without this option, JSX elements are assigned auto-generated numeric placeholders (e.g. `<0>here0>`), which are less readable for translators and may cause issues if the element order changes.
TypeScript Usage
In React/TypeScript projects, you need to declare the custom attribute so that TypeScript doesn't report an error. Add the following to a `.d.ts` file included in your project:
```
import "react";
declare module "react" {
interface Attributes {
_t?: string; // replace with your `jsxPlaceholderAttribute` value
}
}
```
## macro.jsxPlaceholderDefaults[](#macrojsxplaceholderdefaults "Direct link to macro.jsxPlaceholderDefaults")
Default value: `undefined`
A mapping of JSX element tag names to default placeholder names. When a JSX element inside `` matches a key in this map and does not have an explicit placeholder attribute (see [`macro.jsxPlaceholderAttribute`](#macrojsxplaceholderattribute)), the corresponding value is used as the placeholder name.
```
// lingui.config
{
macro: {
jsxPlaceholderAttribute: "_t",
jsxPlaceholderDefaults: {
a: "link",
em: "emphasis",
strong: "bold",
},
}
}
// source
Click here and this;
// extracted message: "Click here and this"
```
Explicit attributes (via `jsxPlaceholderAttribute`) take priority over defaults.
One Name per Distinct Element
A placeholder name can be used only once per message. If two elements in the same `` resolve to the same name but differ in tag or props, for example two `` elements with different `href` values both mapped to `link`, the macro throws an error instead of numbering them (``, ``). Give at least one of them an explicit name via `jsxPlaceholderAttribute`:
```
Read the{" "}
docs
{" "}
or the{" "}
FAQ
.
// extracted message: "Read the docs or the FAQ."
```
Identical elements, such as two ` ` with no props, share a single placeholder without error.
See [Translator-friendly Messages](https://lingui.dev/guides/translator-friendly-messages.md#name-your-tags) for when and why to name tags.
Enforce Named Placeholders with ESLint
You can enforce that all JSX tags in `` have named placeholders across your codebase using the Lingui [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md) rule [`no-unnamed-tag-placeholders`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-unnamed-tag-placeholders.md).
## macro.idPrefixLeader[](#macroidprefixleader "Direct link to macro.idPrefixLeader")
Default value: `undefined`
If defined, the `/* lingui-set idPrefix="..." */`) directive will only prepend `idPrefix` to explicit IDs that start with this leader string. This allows you to selectively apply prefixes to specific IDs while leaving others untouched. The leader string is **kept** in the final ID.
```
// lingui.config
export default {
macro: {
idPrefixLeader: ".",
},
};
```
```
// source
import { Trans } from "@lingui/react/macro"
// lingui-set idPrefix="myPrefix"
With prefix // id="myPrefix.withPrefix"
Unprefixed // id="unprefixed"
```
## macro.jsxRuntime[](#macrojsxruntime "Direct link to macro.jsxRuntime")
Default value: `undefined`
Controls which JSX runtime semantics the Lingui JSX macro emit. Accepts `"react"`, `"solid"` or `"vue"`.
```
// lingui.config
{
macro: {
jsxRuntime: "solid";
}
}
```
## experimental.runtimeMacro[](#experimentalruntimemacro "Direct link to experimental.runtimeMacro")
Default value: `false`
Experimental
This option is experimental and may change in a minor release.
Extracts messages defined with the [runtime macro](https://lingui.dev/ref/core.md#runtime-macro) (imports from `@lingui/core/runtime-macro`) to your catalogs.
```
// lingui.config
{
experimental: {
runtimeMacro: true,
}
}
```
---
# Core API Reference
The `@lingui/core` package provides the main i18n object which manages message catalogs, active locale as well as translation and formatting of messages.
## Installation[](#installation "Direct link to Installation")
* npm
* Yarn
* pnpm
```
npm install --save @lingui/core
```
```
yarn add @lingui/core
```
```
pnpm add @lingui/core
```
## Overview[](#overview "Direct link to Overview")
The `@lingui/core` package provides a global instance of the `i18n` object, which you can import and use directly:
```
import { i18n } from "@lingui/core";
/**
* Load messages for the requested locale and activate it.
* This function isn't part of the Lingui because there are
* many ways how to load messages — from REST API, from file, from cache, etc.
*/
async function activate(locale: string) {
const { messages } = await import(`${locale}/messages.js`);
i18n.loadAndActivate({ locale, messages });
}
activate("cs");
// returns the Czech translation of "Hello World"
const translation = i18n.t("Hello World");
```
Advanced
If you prefer not to use the global `i18n` instance and want to set up your own, you can utilize the [`setupI18n`](#setupi18n) method. Additionally, you'll need to configure the [`runtimeConfigModule`](https://lingui.dev/ref/conf.md#runtimeconfigmodule) to ensure that macros work properly.
## Class `i18n()`[](#i18n "Direct link to i18n")
### `i18n.loadAndActivate(options)`[](#i18n.loadAndActivate "Direct link to i18n.loadAndActivate")
The `options` parameter is an object with the following properties:
* `locale`: The initial active locale.
* `locales`: A list of alternative locales ([BCP-47](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html) language tags) used for number and date formatting.
* `messages`: The **compiled** message catalog.
It allows to set (overwrite) the catalog for a given locale and activate the locale:
```
import { i18n } from "@lingui/core";
const { messages } = await import(`${locale}/messages.js`);
i18n.loadAndActivate({ locale, messages });
```
### `i18n.load(allMessages: AllMessages)`[](#i18n.load\(allMessages\) "Direct link to i18n.load(allMessages)")
### `i18n.load(locale: string, messages: Messages)`[](#i18n.load "Direct link to i18n.load")
Load messages for given locale or load multiple message catalogs at once.
When some messages for the provided locale are already loaded, calling `i18n.load` will merge the new messages with the existing ones using `Object.assign`.
```
import { i18n } from "@lingui/core";
/**
* This is just an example of what the catalog looks like internally.
* Formatting of string messages only works in development. See note below.
*/
const messagesEn = {
Hello: "Hello",
"Good bye": "Good bye",
"My name is {name}": "My name is {name}",
};
const messagesCs = {
Hello: "Ahoj",
"Good bye": "Nashledanou",
"My name is {name}": "Jmenuji se {name}",
};
i18n.load({
en: messagesEn,
cs: messagesCs,
});
// This is the same as loading message catalogs separately per language:
// i18n.load('en', messagesEn)
// i18n.load('cs', messagesCs)
```
tip
Don't write catalogs manually. The code above is an example of message catalogs. In real applications, messages are loaded from external message catalogs generated by the [`compile`](https://lingui.dev/ref/cli.md#compile) command or by using tools such as [Vite Plugin](https://lingui.dev/ref/vite-plugin.md), [Webpack Loader](https://lingui.dev/ref/loader.md), or [Metro Transformer](https://lingui.dev/ref/metro-transformer.md).
Formatting of messages as strings (e.g: `"My name is {name}"`) works in development only, when messages are parsed on the fly. In production, however, messages must be compiled using the [`compile`](https://lingui.dev/ref/cli.md#compile) command.
Here's how the same example would look in a real application:
```
import { i18n } from "@lingui/core";
// File generated by `lingui compile`
import { messages as messagesEn } from "./locale/en/messages.js";
i18n.load("en", messagesEn);
```
### `i18n.setMessagesCompiler(compiler)`[](#i18n.setMessagesCompiler "Direct link to i18n.setMessagesCompiler")
Registers a `MessageCompiler` to enable the use of uncompiled catalogs at runtime.
In production builds, the `MessageCompiler` is typically excluded to reduce bundle size.
By default, message catalogs should be precompiled during the build process. However, if you need to compile catalogs at runtime, you can use this method to set a message compiler.
Example usage:
```
import { compileMessage } from "@lingui/message-utils/compileMessage";
i18n.setMessagesCompiler(compileMessage);
```
### `i18n.activate(locale[, locales])`[](#i18n.activate "Direct link to i18n.activate")
Activate the specified locale and any alternate locales. After calling this method, calling `i18n.t` will return messages in the activated locale.
```
import { i18n } from "@lingui/core";
i18n.activate("en");
i18n.t("Hello"); // Return "Hello" in English
i18n.activate("cs");
i18n.t("Hello"); // Return "Hello" in Czech
```
### `i18n.t(messageId[, values[, options]])`[](#i18n.t "Direct link to i18n.t")
The core method for translating and formatting messages.
* `messageId`: a unique message ID which identifies message in catalog.
* `values`: an object containing variables used in translated message.
* `options.message`: the default translation (optional). This is mostly used when application doesn't use message IDs in natural language (e.g.: `msg.id` or `Component.title`).
* `options.formats`: custom format definitions for dates and times (optional). An object where keys are format names and values are either `Intl.DateTimeFormatOptions` or `Intl.NumberFormatOptions`.
```
import { i18n } from "@lingui/core";
// Simple message
i18n.t("Hello");
// Message with variables
i18n.t("My name is {name}", { name: "Tom" });
// Message with custom messageId
i18n.t("msg.id", { name: "Tom" }, { message: "My name is {name}" });
const date = new Date("2014-12-06");
const time = new Date("2014-12-06T17:40:00Z");
// Short date format
i18n.t("It starts on {someDate, date, short}", { someDate: date });
// Short time format
i18n.t("It starts on {someTime, time, short}", { someTime: time });
// Date skeleton format
i18n.t("It starts on {someDate, date, ::GrMMMdd}", { someDate: date });
// Custom date format
i18n.t("It starts on {someDate, date, myStyle}", { someDate: date }, { formats: { myStyle: { day: "numeric" } } });
```
### `i18n.t(messageDescriptor)`[](#i18ntmessagedescriptor "Direct link to i18ntmessagedescriptor")
`messageDescriptor` is an object with a message ID, default message and other parameters. It's useful when you need to use the declared message later in the code.
```
import { i18n } from "@lingui/core";
// Simple message
i18n.t({ id: "Hello" });
// Simple message using custom ID
i18n.t({ id: "msg.hello", message: "Hello" });
// Message with variable
i18n.t({ id: "My name is {name}", values: { name: "Tom" } });
// Message with comment, custom ID and variable
i18n.t({
id: "msg.name",
message: "My name is {name}",
comment: "Message showing the passed in name",
values: { name: "Tom" },
});
```
Read more about [Message Descriptor](https://lingui.dev/ref/macro.md#core-macros).
### `i18n._(...)`[](#i18n._ "Direct link to i18n._")
Canonical translation method. [`i18n.t`](#i18n.t) is an alias for this method.
```
import { i18n } from "@lingui/core";
i18n._({ id: "Hello" });
```
### `i18n.setVariables(variables)`[](#i18n.setvariables "Direct link to i18n.setvariables")
Set default values for message variables when they are not passed to [`i18n.t`](#i18n.t). Accepts an object of static values or lazy functions, or an updater `(prev) => next`.
```
import { i18n } from "@lingui/core";
i18n.setVariables({
appName: "ExampleApp",
version: "1.2.3",
});
i18n.t("Powered by {appName} v{version}");
// Returns "Powered by ExampleApp v1.2.3"
```
Advanced
Default variables also work for placeholders that only exist in translations, like `{gender, select, ...}`. Since the placeholder isn't in the source string, the `select` must be added by your translation pipeline or translators who know the variable exists.
### `i18n.setVariable(name, value)`[](#i18n.setvariable "Direct link to i18n.setvariable")
Set or update a single default variable, or pass `undefined` to remove it.
```
import { i18n } from "@lingui/core";
i18n.setVariable("appName", "ExampleApp");
i18n.setVariable("currentYear", () => new Date().getFullYear());
i18n.setVariable("appName", undefined);
```
### `i18n.date(value: string | Date | number[, format: Intl.DateTimeFormatOptions])`[](#i18n.date "Direct link to i18n.date")
Format a date using the conventional format for the active language.
* `value`: the date to be formatted, as accepted by [`Intl.DateTimeFormat.prototype.format`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format#parameters). When `value` is a string, a `Date` object is created using `new Date(date)`.
* `format`: an optional object that is passed to the `options` argument of the [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor. This allows for customization of the date formatting.
Deprecated
`i18n.date` will be removed. Prefer using `Intl.DateTimeFormat` directly:
```
new Intl.DateTimeFormat(i18n.locale, format).format(d);
```
```
import { i18n } from "@lingui/core";
const d = new Date("2021-07-23T16:23:00");
i18n.activate("en");
i18n.date(d);
// Returns "7/23/2021"
i18n.date(d, { timeStyle: "medium" });
// Returns "4:23:00 PM"
i18n.date(d, { dateStyle: "medium", timeStyle: "medium" });
// Returns "Jul 23, 2021, 4:23:00 PM"
i18n.activate("cs");
i18n.date(d);
// Returns "23. 7. 2021"
```
### `i18n.number(value: number | bigint | Intl.StringNumericLiteral[, format: Intl.NumberFormatOptions])`[](#i18n.number "Direct link to i18n.number")
Format a number using the conventional format for the active language.
* `value`: the number to be formatted, as accepted by [`Intl.NumberFormat.prototype.format`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format#parameters).
* `format`: an optional object that is passed to the `options` argument of the [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) constructor. This allows for customization of the date formatting.
Deprecated
`i18n.number` will be removed. Prefer using `Intl.NumberFormat` directly:
```
new Intl.NumberFormat(i18n.locale, format).format(value);
```
```
import { i18n } from "@lingui/core";
i18n.activate("en");
i18n.number(12345.678);
// Returns "12,345.678"
i18n.number(12345.678, { style: "currency", currency: "USD" });
// Returns "$12,345.68"
i18n.activate("cs");
i18n.number(12345.678);
// Returns "12 345,678"
i18n.number(12345.678, { style: "currency", currency: "CZK" });
// Returns "12 345,68 Kč"
```
## `setupI18n([options])`[](#setupi18n "Direct link to setupi18n")
Initialize and return a new `I18n` instance. Typically, you should call this function only once and then use the returned `i18n` object throughout your entire codebase.
info
You typically don't need to set up your own `i18n` instance. In most cases, you can use the global `i18n` object exported from `@lingui/core` directly.
However, if you need to do this, make sure to also configure the [`runtimeConfigModule`](https://lingui.dev/ref/conf.md#runtimeconfigmodule) to ensure macros work properly.
```
import { setupI18n } from "@lingui/core";
const i18n = setupI18n();
```
The factory function accepts an optional `options` parameter, which can be used to configure the initial state of the `i18n` instance.
### `options.locale`[](#optionslocale "Direct link to optionslocale")
Initial active locale.
```
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({ locale: "en" });
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.activate("en")
```
### `options.locales`[](#optionslocales "Direct link to optionslocales")
List of alternative locales ([BCP-47](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html) language tags) which are used for number and date formatting (some countries use more than one number/date format). If not set, the active locale is used instead.
```
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({
locale: "ar",
locales: ["en-UK", "ar-AS"],
});
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.activate("ar", ["en-UK", "ar-AS"])
```
### `options.messages`[](#optionsmessages "Direct link to optionsmessages")
Initial [`Messages`](#messages).
```
import { setupI18n } from "@lingui/core";
const messages = {
en: require("./locale/en/messages").messages, // your path to compiled messages here
cs: require("./locale/cs/messages").messages, // your path to compiled messages here
};
const i18n = setupI18n({ messages });
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.load(messages)
```
### `options.missing`[](#optionsmissing "Direct link to optionsmissing")
A custom message to be returned when a translation is missing. This feature is useful for debugging:
```
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({ missing: "🚨" });
i18n.t("missing translation") === "🚨"; // Returns the custom missing message
```
Alternatively, `missing` can be a function that receives the active locale and message ID as arguments:
```
import { setupI18n } from "@lingui/core";
function missing(locale, id) {
alert(`Translation in ${locale} for ${id} is missing!`);
return id;
}
const i18n = setupI18n({ missing });
i18n.t("missing translation"); // Triggers an alert
```
### `options.variables`[](#optionsvariables "Direct link to optionsvariables")
Initial default message variables (see [`i18n.setVariables`](#i18n.setvariables)).
```
import { setupI18n } from "@lingui/core";
const i18n = setupI18n({
variables: {
appName: "ExampleApp",
version: "1.2.3",
},
});
// This is a shortcut for:
// const i18n = setupI18n()
// i18n.setVariables({ appName: "ExampleApp", version: "1.2.3" })
```
## Runtime macro (experimental)[](#runtime-macro "Direct link to Runtime macro (experimental)")
Experimental
The runtime macro is experimental. Its API and import path may change in a minor release.
`@lingui/core/runtime-macro` exports `msg` (and its alias `defineMessage`), `plural`, `select` and `selectOrdinal` as plain functions. They work without a Babel or SWC plugin, so you can use them where there is no build step: Node.js scripts, serverless functions, CLI tools or test runners.
They return the same [Message Descriptor](https://lingui.dev/ref/macro.md#core-macros), with the same generated ID, as the [core macros](https://lingui.dev/ref/macro.md#core-macros). The extractor picks them up when [`experimental.runtimeMacro`](https://lingui.dev/ref/conf.md#experimentalruntimemacro) is enabled in your config.
```
import { i18n } from "@lingui/core";
import { msg, plural } from "@lingui/core/runtime-macro";
const greeting = msg`Hello ${{ name }}`;
i18n._(greeting);
const inbox = msg`You have ${plural({ count }, { one: "# message", other: "# messages" })}`;
i18n._(inbox);
const welcome = msg({ message: "Welcome back", context: "homepage" });
i18n._(welcome);
```
The runtime macro supports a subset of the core macros, with a few differences:
* **Placeholders must be named.** Variable names can't be read at runtime, so write `${{ name }}` instead of `${name}`. A plain value throws an error.
* **Option values can't be template literals.** Use a nested `msg` instead: ``select({ gender }, { female: msg`She is ${{ name }}`, other: msg`They are ${{ name }}` })``.
* **Write exact matches first, in ascending order.** JavaScript puts integer keys before the other keys of an object, so `plural({ count }, { one: "...", 0: "...", other: "..." })` and `{ 1: "...", 0: "..." }` produce a different message, and so a different ID, than the core macros. Write `{ 0: "...", 1: "...", one: "...", other: "..." }` instead.
* **No `t` and no JSX.** Define a message with `msg` and translate it with [`i18n._`](#i18n._). If you prefer a shorter call, `const t = i18n.t` works too.
* **Use `plural`, `select` and `selectOrdinal` inside `msg`.** On their own, they return a Message Descriptor at runtime, but a build step that compiles them (see below) turns them into a translated string, like the core macros. Inside `msg`, both give the same result.
* **Without a compile step, the source message stays in your bundle.** The compile-time macros can strip it in production.
With [`experimental.runtimeMacro`](https://lingui.dev/ref/conf.md#experimentalruntimemacro) enabled, the Babel macro plugin and the [Vite native transform](https://lingui.dev/ref/vite-plugin.md) also compile these imports at build time, like the core macros. The [SWC plugin](https://lingui.dev/ref/swc-plugin.md) doesn't read the Lingui config: add `@lingui/core/runtime-macro` to its `corePackage` option if you want the same there. Without compilation, the code still works as it is.
## AllMessages[](#allmessages "Direct link to AllMessages")
The `AllMessages` parameter in the [`I18n.load`](#i18n.load) method is of the following type:
```
type AllMessages = { [locale: string]: CompiledMessage };
// Example
const messages: AllMessages = {
en: {
messages: {
Hello: "Hello",
"Good bye": "Good bye",
},
},
cs: {
messages: {
Hello: "Ahoj",
"Good bye": "Nashledanou",
},
},
};
```
## Messages[](#messages "Direct link to Messages")
Type of messages in [`AllMessages`](#allmessages). It's a mapping of a message ID to a translation in given language. This may be a function if messages are compiled.
```
type Messages = { [messageId: string]: string | Function };
// Example
const messagesEn: Messages = {
Hello: "Hello",
"Good bye": "Good bye",
};
```
## Events[](#events "Direct link to Events")
### `change`[](#change "Direct link to change")
The `change` event is triggered **after** changing the locale, loading a new message catalog, or updating default variables. No arguments are passed to this event.
### `missing`[](#missing "Direct link to missing")
The `missing` event is triggered when a translation is requested using [`i18n.t`](https://lingui.dev/ref/core.md#i18n.t) that does not exist in the messages of the active locale. The event provides information about the locale and the missing message ID.
```
i18n.on("missing", (event) => {
alert(`Translation in ${event.locale} for ${event.id} is missing!`);
});
```
---
# ESLint Plugin
Lingui provides an ESLint plugin to help you find common Lingui usage errors in your code.
[](https://www.npmjs.com/package/eslint-plugin-lingui) [](https://www.npmjs.com/package/eslint-plugin-lingui)
## Installation[](#installation "Direct link to Installation")
Install [ESLint](http://eslint.org):
* npm
* Yarn
* pnpm
```
npm install --save-dev eslint
```
```
yarn add --dev eslint
```
```
pnpm add --save-dev eslint
```
Next, install `eslint-plugin-lingui`:
* npm
* Yarn
* pnpm
```
npm install --save-dev eslint-plugin-lingui
```
```
yarn add --dev eslint-plugin-lingui
```
```
pnpm add --save-dev eslint-plugin-lingui
```
info
If you have installed ESLint globally (using the `-g` flag), you must also install `eslint-plugin-lingui` globally.
## Usage[](#usage "Direct link to Usage")
### Flat Config (`eslint.config.js`)[](#flat-config "Direct link to flat-config")
Version 8 of ESLint introduced a new configuration format called [Flat Config](https://eslint.org/docs/latest/use/configure/configuration-files). Flat config files represent plugins and parsers as JavaScript objects.
#### Recommended Setup[](#recommended-setup "Direct link to Recommended Setup")
To enable all the recommended rules for the plugin, add the following config:
```
import pluginLingui from "eslint-plugin-lingui";
export default [
pluginLingui.configs["flat/recommended"],
// Any other config...
];
```
#### Custom Setup[](#custom-setup "Direct link to Custom Setup")
Alternatively, you can load the plugin and configure only the rules you want to use:
```
import pluginLingui from "eslint-plugin-lingui";
export default [
{
plugins: {
lingui: pluginLingui,
},
rules: {
"lingui/t-call-in-function": "error",
},
},
// Any other config...
];
```
### Legacy Config (`.eslintrc`)[](#legacy-eslintrc "Direct link to legacy-eslintrc")
The legacy configuration format has been deprecated by ESLint, but it's still supported. If you're using the legacy format, you can use the following configuration.
#### Recommended Setup[](#recommended-setup-1 "Direct link to Recommended Setup")
To enable all the recommended rules for the plugin, add `plugin:lingui/recommended` to the `extends` section:
```
{
"extends": ["plugin:lingui/recommended"]
}
```
#### Custom Setup[](#custom-setup-1 "Direct link to Custom Setup")
Alternatively, add `lingui` to the `plugins` section of your `.eslintrc` configuration file. You can omit the `eslint-plugin-` prefix:
```
{
"plugins": ["lingui"]
}
```
In the rules section, configure the rules you want to use. For example:
```
{
"rules": {
"lingui/no-unlocalized-strings": 2,
"lingui/t-call-in-function": 2,
"lingui/no-single-variables-to-translate": 2,
"lingui/no-expression-in-message": 2,
"lingui/no-single-tag-to-translate": 2,
"lingui/no-trans-inside-trans": 2,
"lingui/no-unnamed-tag-placeholders": 2
}
}
```
### Oxlint[](#oxlint "Direct link to Oxlint")
The plugin also works as an [Oxlint JS plugin](https://oxc.rs/docs/guide/usage/linter/js-plugins) without any changes. Add it to `jsPlugins` in your `.oxlintrc.json` and enable the rules you need.
Oxlint doesn't read the plugin's `configs`, so the recommended rules have to be listed explicitly:
```
{
"jsPlugins": ["eslint-plugin-lingui"],
"rules": {
"lingui/t-call-in-function": "error",
"lingui/no-single-tag-to-translate": "warn",
"lingui/no-single-variables-to-translate": "warn",
"lingui/no-trans-inside-trans": "warn",
"lingui/no-expression-in-message": "warn"
}
}
```
Compatibility with Oxlint is verified in CI on every change. The only known limitation is the `useTsTypes` option of the [`no-unlocalized-strings`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-unlocalized-strings.md) rule: it needs type information from `@typescript-eslint/parser`, which Oxlint doesn't provide.
tip
See the [official repository](https://github.com/lingui/eslint-plugin) for more information about the rules.
---
# Vue.js Extractor
The `@lingui/extractor-vue` package provides a custom extractor that handles Vue.js files.
It extracts messages from `
```
Imports in templates
Import `Trans`, `Plural`, `Select`, `SelectOrdinal` and `useLingui` from `@lingui/vue/macro` in `
Link to docs
```
Using a tag name or a render function:
```
Link to docsSign in
```
## Lingui Context[](#lingui-context "Direct link to Lingui Context")
Message catalogs and the active locale are provided through Vue's provide/inject in the [`I18nProvider`](#i18nprovider). You can access this context using the [`useLingui`](#uselingui) composable.
The `LinguiInjectionKey` symbol is exported from the `@lingui/vue` package. While most users will not need to interact with it directly, it can be useful for advanced scenarios where the default behavior of `I18nProvider` doesn't meet your specific needs.
### `I18nProvider`[](#i18nprovider "Direct link to i18nprovider")
The `I18nProvider` provides Lingui context to all components in the subtree. It should be rendered as top-level component of your application.
It ensures that its children are only rendered after a locale has been activated, guaranteeing that any components relying on `i18n` have access to the translations. Additionally, the `I18nProvider` subscribes to change events emitted by the `i18n` object, automatically updating components that consume the Lingui context whenever messages are updated or a new locale is activated.
| Prop name | Type | Description |
| ------------------ | ----------- | ---------------------------------------------------------------------------- |
| `i18n` | `I18n` | The `I18n` object instance (usually the one imported from `@lingui/core`) |
| `defaultComponent` | `Component` | A Vue component within which translation strings will be rendered (optional) |
The `defaultComponent` serves the same purpose as the `component` prop in other i18n components. For a detailed explanation of how translations are rendered, see the [Rendering of Translations](#rendering-translations) section at the beginning of this document.
#### Examples[](#examples-1 "Direct link to Examples")
src/App.vue
```
```
### `createLingui`[](#createlingui "Direct link to createlingui")
`createLingui` is a Vue plugin alternative to the `I18nProvider` component. It provides the Lingui context to the whole application:
src/main.ts
```
import { createApp } from "vue";
import { i18n } from "@lingui/core";
import { createLingui } from "@lingui/vue";
import App from "./App.vue";
i18n.load("en", messages);
i18n.activate("en");
createApp(App).use(createLingui({ i18n })).mount("#app");
```
| Option | Type | Description |
| ------------------ | ----------- | ---------------------------------------------------------------- |
| `i18n` | `I18n` | The `I18n` object instance |
| `defaultComponent` | `Component` | Same as the `defaultComponent` prop of `I18nProvider` (optional) |
Unlike `I18nProvider`, the plugin does not wait for `i18n.activate()` before rendering the application.
### `useLingui`[](#uselingui "Direct link to uselingui")
The `useLingui` composable provides access to the Lingui context. It returns an object with the following properties:
| Key | Type | Description |
| ------------------ | ------------------ | --------------------------------------------------------------------------------------------- |
| `i18n` | `ShallowRef` | Reactive reference to the `I18n` object instance that you passed to `I18nProvider` |
| `_` | `I18n["_"]` | Reference to the [`i18n._`](https://lingui.dev/ref/core.md#i18n._) function, explained below |
| `t` | `I18n["_"]` | Alias of `_`, called by templates compiled with the [template transform](#template-transform) |
| `defaultComponent` | `Component` | The same `defaultComponent` you passed to `I18nProvider`, if provided |
The `i18n` value returned from `useLingui` is a shallow ref that is triggered whenever the locale or the catalogs change. Read `i18n.value.locale` in a `computed` or in the render function to react to updates. In templates and `
{{ label }}: {{ i18n.locale }}
```
tip
There is a [macro version](https://lingui.dev/ref/macro.md#uselingui) of the `useLingui` composable which supports all features of the [`t` macro](https://lingui.dev/ref/macro.md#t) and uses the runtime `useLingui` composable (from `@lingui/vue`) under the hood:
```
```
In templates, `` t`...` `` is compiled by the [template transform](#template-transform) into a call of the same `t` function, so one `useLingui()` in `
```
#### Plurals[](#plurals "Direct link to Plurals")
If for some reason you cannot use the template transform, you can render plurals using the simple `Trans` component by passing the [ICU MessageFormat](https://lingui.dev/guides/message-format.md) string as the `message` prop:
```
```
---
# Crowdin

Crowdin is a localization management platform that helps translate your LinguiJS-based product. Automate localization, release several multilingual versions of your app simultaneously, and provide an enhanced experience for your global customers.
[Website](https://crowdin.com/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev) | [GitHub](https://github.com/crowdin) | [Support](https://crowdin.com/contacts?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev)
## Features[](#features "Direct link to Features")
### Keep all translations in one place while connecting your teams via Crowdin[](#keep-all-translations-in-one-place-while-connecting-your-teams-via-crowdin "Direct link to Keep all translations in one place while connecting your teams via Crowdin")
Connect with your content, marketing, and translation teams in one collaborative space:
* Screenshots for additional context.
* Highlight HTML, placeholders, plurals, and more.
* Describe the context and set character limits to ensure the translation fits the UI.
* All translations are done online or can be uploaded to the platform.
* Jira integration to notify you about source string issues.
* Tips for translators to ensure there is no extra space or broken code.
### Ship faster with localization running in parallel[](#ship-faster-with-localization-running-in-parallel "Direct link to Ship faster with localization running in parallel")
Keep developing new features and improvements while translators receive new texts in real-time. Release multilingual versions for customers around the globe simultaneously.
### Release your product in several languages at once[](#release-your-product-in-several-languages-at-once "Direct link to Release your product in several languages at once")
Help users from different regions use the latest version of your product in their language:
* Get feature branches translated independently from the master branch.
* Translators work together in one place to boost productivity.
* Never deal with translations in spreadsheets or email attachments.
* Source texts are updated for translators automatically and in real-time.
* Automatically pull completed translations that are ready to be merged.
### Seamlessly integrate localization during any phase of your development cycle[](#seamlessly-integrate-localization-during-any-phase-of-your-development-cycle "Direct link to Seamlessly integrate localization during any phase of your development cycle")
Automate the integration of source texts and translations between Crowdin and your source code with one-click integration or customizable solutions.
### Define your translation strategy[](#define-your-translation-strategy "Direct link to Define your translation strategy")
Decide who will translate your content:
* Invite your team of translators (in-house translators, freelancers, or translation agencies you already work with).
* Order professional translations from a vendor (translation agency) from Crowdin Vendors Marketplace.
* Configure machine translation engines.
* Engage your community.
### VCS: GitHub, GitLab, Bitbucket[](#vcs-github-gitlab-bitbucket "Direct link to VCS: GitHub, GitLab, Bitbucket")
Source strings are pulled automatically and are always up to date for your translators. Translated content is automatically pushed to your repository as a request.

## CLI[](#cli "Direct link to CLI")
Connect cross-platform [Crowdin CLI](https://crowdin.github.io/crowdin-cli/) directly to your code repository and never deal with localization files manually again.
With Crowdin CLI, you can:
* Automate the process of updating your source files in your Crowdin project.
* Download translations from Crowdin and automatically save them in the correct locations.
* Upload all your existing translations to Crowdin in minutes.
### Create the `crowdin.yml` configuration file[](#create-the-crowdinyml-configuration-file "Direct link to create-the-crowdinyml-configuration-file")
crowdin.yml
```
project_id: "123456" # Your Crowdin project ID
api_token_env: CROWDIN_PERSONAL_TOKEN
preserve_hierarchy: true
files: # Paths to the source and translation files
- source: /**/locales/en/*
translation: /**/locales/%two_letters_code%/%original_file_name%
```
### Install the Crowdin CLI as an npm package[](#install-the-crowdin-cli-as-an-npm-package "Direct link to Install the Crowdin CLI as an npm package")
* npm
* Yarn
* pnpm
```
npm install --save-dev @crowdin/cli
```
```
yarn add --dev @crowdin/cli
```
```
pnpm add --save-dev @crowdin/cli
```
### Add the synchronization scripts[](#add-the-synchronization-scripts "Direct link to Add the synchronization scripts")
Add the following scripts to your `package.json`:
package.json
```
{
"scripts": {
"crowdin": "crowdin",
"sync": "crowdin push && crowdin pull",
"sync:sources": "crowdin push",
"sync:translations": "crowdin pull"
}
}
```
### Configuration[](#configuration "Direct link to Configuration")
Set the `CROWDIN_PERSONAL_TOKEN` env variable on your computer, to allow the CLI to authenticate with the Crowdin API.
#### Usage[](#usage "Direct link to Usage")
Test that you can run the Crowdin CLI:
* npm
* Yarn
* pnpm
```
npm run crowdin --version
```
```
yarn crowdin --version
```
```
pnpm run crowdin --version
```
Upload all the source files to Crowdin:
* npm
* Yarn
* pnpm
```
npm run sync:sources
```
```
yarn sync:sources
```
```
pnpm run sync:sources
```
Download translation files from Crowdin:
* npm
* Yarn
* pnpm
```
npm run sync:translations
```
```
yarn sync:translations
```
```
pnpm run sync:translations
```
Upload sources to Crowdin and download translations from Crowdin:
* npm
* Yarn
* pnpm
```
npm run sync
```
```
yarn sync
```
```
pnpm run sync
```
To run other Crowdin CLI commands you can use the following command:
* npm
* Yarn
* pnpm
```
npm run crowdin
```
```
yarn crowdin
```
```
pnpm run crowdin
```
To see the full list of possible commands and options:
* npm
* Yarn
* pnpm
```
npm run crowdin -h
```
```
yarn crowdin -h
```
```
pnpm run crowdin -h
```
## Over-The-Air Content Delivery[](#over-the-air-content-delivery "Direct link to Over-The-Air Content Delivery")
Over-the-Air Content Delivery is a feature that allows you to instantly update sources and translations in your mobile, server, desktop, or web apps with a single click without preparing a new release.
Visit the following pages to learn more about how to integrate Over-The-Air Content Delivery into your Lingui project:
* [Lingui tutorial - Crowdin OTA JS Client](https://crowdin.github.io/ota-client-js/tutorials/lingui/)
* [Lingui String Exporter - Crowdin Marketplace](https://store.crowdin.com/lingui-string-exporter?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev)
## API and Webhooks[](#api-and-webhooks "Direct link to API and Webhooks")
Customize your experience. Automate and scale your localization workflow. Seamlessly add new content for translation to your Crowdin project, check translation status, merge new content, etc.
See the [API](https://support.crowdin.com/developer/api/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev) and [Webhooks](https://support.crowdin.com/developer/webhooks/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev) documentation for more information.
## Next Steps[](#next-steps "Direct link to Next Steps")
To get started, register a [Crowdin.com](https://accounts.crowdin.com/register?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev) or [Crowdin Enterprise](https://accounts.crowdin.com/workspace/create?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev) account. Once you have signed up, [create your localization project](https://support.crowdin.com/creating-project/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev).
Depending on how you'd like to work with Crowdin, you have the following options:
1. [Integrate Crowdin with GitHub](https://support.crowdin.com/github-integration/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev).
2. Manage and synchronize your localization resources with [Crowdin CLI](https://developer.crowdin.com/cli-tool/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev).
3. [Upload files for the test via UI](https://support.crowdin.com/uploading-files/?utm_source=lingui.dev\&utm_medium=referral\&utm_campaign=lingui.dev).
---
# Sync & Collaboration Tools
While Lingui provides a powerful API for managing your translations, it doesn't provide an integrated solution for managing synchronization and collaboration with your translators.
This guide covers tools that can help you manage your localization process. You may come across acronyms like TMS (Translation Management System) or CAT (Computer Aided Translation) that are sometimes used to describe these tools.
## Workflows[](#workflows "Direct link to Workflows")
The easiest way to translate your application is to translate your message catalogs directly in a text editor, or with a tool like [Poedit](https://poedit.net).
This solution may be good enough when your application is small and doesn't evolve much, but it quickly becomes hard work as the number of sentences to translate and target languages to manage increases over time.
It becomes increasingly difficult and time-consuming to manage the back-and-forth with translators while keeping your application's message catalogs up to date with the current state of a codebase that does not stop evolving.
### Regular Workflow[](#regular-workflow "Direct link to Regular Workflow")

This is the most basic workflow which involves sending the `.po` files to your translators (usually by email) and syncing them back manually into your application.
This workflow is manageable when your application is still quite small, doesn't contain a lot of text, and doesn't evolve much.
### Sync & Collaboration Tool Workflow[](#sync--collaboration-tool-workflow "Direct link to Sync & Collaboration Tool Workflow")

When the amount of text to translate increases, and the number of target languages grows, it becomes more efficient to use a sync and collaboration tool to assist you with the management of your team of translators, and co-evolution between your code and the translated files.
Instead of manually sending and receiving many emails and fixing the inconsistencies with your code, a `sync` method is called and your `.po` and `.js` files are directly updated with the latest translations. Your translators will also be notified when there are new text to translate.
## Benefits[](#benefits "Direct link to Benefits")
* **Synchronization**: unique `yarn sync` or `npm run sync` command to synchronize your project with all your translators and update your local `.po` and `.js` files with the latest translations.
* **Translation Interface**: provide a professional and flexible interface to translators.
* **Translation Memory**: assist translators by suggesting previously translated sentences that are similar.
* **Machine Translation**: auto-translate with Google Translate, DeepL, etc. and human-proofread later.
* **Smart Plural Management**: allows to translate `Message` and `Messages` instead of `{count, plural, one {Message} other {Messages}}`.
* **Consistency**: assist translators with `{variable}` interpolation and HTML formatting.
## Available Tools[](#available-tools "Direct link to Available Tools")
* [Crowdin](https://lingui.dev/tools/crowdin.md)
* [Translation.io](https://lingui.dev/tools/translation-io.md)
---
# Translation.io

Translation.io is a professional synchronization and collaboration platform that will assist your team in the translation of your Lingui application.
[Website](https://translation.io/lingui) | [GitHub](https://github.com/translation/lingui) |
## Features[](#features "Direct link to Features")
### Smooth Team Management[](#smooth-team-management "Direct link to Smooth Team Management")
Invite collaborators using their email or username, and assign them a role and a target language. They will be brought on board and kept informed about any new activity in their language.

Learn more:
* [Fine-Grained Authorizations](https://translation.io/blog/fine-grained-authorization-and-role-management?default_stack=lingui)
* [Activity Digests](https://translation.io/blog/better-history-and-activity-email-digests?default_stack=lingui)
### Elegant Translation Process[](#elegant-translation-process "Direct link to Elegant Translation Process")
Our interface was designed to be the most ergonomic way to translate. It provides translation suggestions (from [TM](https://en.wikipedia.org/wiki/Translation_memory), Google Translate or DeepL), context, discussion and history.
Keyboard shortcuts allow translators to stay focused on their work, visual hints indicate when something went wrong, for example when an interpolated variable or HTML tag is missing.

Learn more:
* [Keyboard Shortcuts](https://translation.io/blog/shortcuts-and-translation?default_stack=lingui)
* [History and Activity Digests](https://translation.io/blog/better-history-and-activity-email-digests?default_stack=lingui)
### Syntax Highlighting[](#syntax-highlighting "Direct link to Syntax Highlighting")
Sometimes you have no choice but to confront your translators with HTML or interpolated variables. The problem is that translators do not necessarily know the meaning of these notations and may be tempted to translate them or may inadvertently alter them.
`Hello {name}` should never be translated as `Bonjour {nom}`, and several mechanisms are in place to ensure this, such as warnings and auto-completion:

***

### Smart Plural Management[](#smart-plural-management "Direct link to Smart Plural Management")
Lingui allows to write plurals using the [ICU MessageFormat](https://lingui.dev/guides/message-format.md) syntax that looks like this:
```
{count, plural, =0 {No messages}
one {# message}
other {# messages}}
```
But you can't ask a translator to understand this syntax, and he or she would be tempted to translate `one` or `other` keywords in other languages, breaking your code at the same time.
That's why plural syntaxes are deconstructed to make translation easier, and then reconstructed in the local `.po` files.
If the target language has more plural forms than the source language, examples are also provided to the translator, as it may be unclear which plural form the `few` or `other` keyword refers to in that specific target language (for instance, Czech has three plural forms).

### Efficient Search[](#efficient-search "Direct link to Efficient Search")
Our powerful search helps translators to maintain consistency of terms throughout their work. In addition, they are able to filter depending on a particular source file or context. To provide a more enjoyable experience, this lightning-fast search works without any page reloading.

Learn more:
* [Smart URLs](https://translation.io/blog/smart-urls-in-translation-interface?default_stack=lingui)
### Adaptive Workflows using Tags[](#adaptive-workflows-using-tags "Direct link to Adaptive Workflows using Tags")
Our interface is flexible enough to adapt to your own translation workflows. Add custom tags to your segments and you'll be directly able to filter them. Moreover, these tags will appear in the statistics page so you can use them for reporting.

Learn more:
* [How to Use Tags](https://translation.io/blog/tags-work-better-as-a-team?default_stack=lingui)
* [Project Statistics](https://translation.io/blog/translation-project-statistics?default_stack=lingui)
## Installation[](#installation "Direct link to Installation")
### Create your Lingui project[](#create-your-lingui-project "Direct link to Create your Lingui project")
Create an account on [Translation.io](https://translation.io/lingui) and create a new Lingui project.
### Configure your application[](#configure-your-application "Direct link to Configure your application")
Copy the `.linguirc` configuration file that was generated for you to the root of your application.
The configuration file looks like this:
.linguirc
```
{
[...]
"format": "po",
"service": {
"name": "TranslationIO",
"apiKey": "abcdefghijklmnopqrstuvwxyz012345"
}
}
```
The synchronization will then be part of the [`extract`](https://lingui.dev/ref/cli.md#extract) command.
### Add the following scripts[](#add-the-following-scripts "Direct link to Add the following scripts")
Add these lines to your `package.json` to make your life easier.
package.json
```
{
"scripts": {
"sync": "lingui extract --overwrite && lingui compile",
"sync_and_purge": "lingui extract --overwrite --clean && lingui compile"
}
}
```
### Initialize your project[](#initialize-your-project "Direct link to Initialize your project")
Initialize your project and upload your source text and potential existing translations with:
* npm
* Yarn
* pnpm
```
npm run sync
```
```
yarn sync
```
```
pnpm run sync
```
## Usage[](#usage "Direct link to Usage")
### Sync[](#sync "Direct link to Sync")
To send new translatable strings and get new translations from Translation.io, and at the same time generate the minified JavaScript catalog files, simply run:
* npm
* Yarn
* pnpm
```
npm run sync
```
```
yarn sync
```
```
pnpm run sync
```
### Sync and Purge[](#sync-and-purge "Direct link to Sync and Purge")
If you need to remove unused strings from Translation.io, using the current branch as reference.
As the name says, this operation will also perform a sync at the same time.
**Warning**: all strings that are not present in the current local branch will be **permanently deleted from Translation.io**.
* npm
* Yarn
* pnpm
```
npm run sync_and_purge
```
```
yarn sync_and_purge
```
```
pnpm run sync_and_purge
```
---
# JavaScript Apps Internationalization
This tutorial will walk you through using Lingui's internationalization (i18n) features in a vanilla JavaScript application. We'll cover the essentials of the `@lingui/core` package, which handles all translation and message catalog management.
Example
If you're looking for a working solution, check out the [Vanilla JS example](https://github.com/lingui/js-lingui/tree/main/examples/js). This example application shows a complete setup using Lingui and vanilla JavaScript.
## Installing Lingui[](#installing-lingui "Direct link to Installing Lingui")
1. Follow the [Installation and Setup](https://lingui.dev/installation.md) page for initial setup.
2. Install the [`@lingui/core`](https://lingui.dev/ref/core.md) package, which is responsible for translation and message catalog handling.
## Setting up i18n[](#setting-up-i18n "Direct link to Setting up i18n")
First, we need to set up the i18n singleton, which is pretty simple:
```
import { i18n } from "@lingui/core";
import { messages } from "path-to-locale/en/messages.js";
i18n.load("en", messages);
i18n.activate("en");
```
The `messages.js` is generated by the Lingui CLI and contains compiled message catalogs.
tip
Alternatively, you can load catalogs dynamically using the [`@lingui/loader`](https://lingui.dev/ref/loader.md) or [`@lingui/vite-plugin`](https://lingui.dev/ref/vite-plugin.md) without the need to import compiled messages manually.
## Localizing Your App[](#localizing-your-app "Direct link to Localizing Your App")
To localize your application, you need to wrap your localizable texts in [Macros](https://lingui.dev/ref/macro.md). Lingui provides a set of Core Macros that transform tagged template literals and can be used in any JavaScript context.
tip
Macros need a compiler plugin, such as Babel or SWC. For code that runs without a build step, see the experimental [runtime macro](https://lingui.dev/ref/core.md#runtime-macro).
Let's wrap our text in the [`t`](https://lingui.dev/ref/macro.md#t) macro:
```
import { t } from "@lingui/core/macro";
t`Hello World!`;
// becomes "Salut le monde!"
const name = "Fred";
t`My name is ${name}`;
// becomes "Je m'appelle Fred"
```
Plurals and selections are possible using [`plural`](https://lingui.dev/ref/macro.md#plural) and [`select`](https://lingui.dev/ref/macro.md#select) macros:
```
import { plural } from "@lingui/core/macro";
const count = 42;
plural(count, {
one: "# book",
other: "# books",
});
// becomes "42 livres"
```
It's also possible to nest message formats. Each message format method in `i18n` has a standalone companion, which only returns message without performing the translation:
```
import { t, select, plural } from "@lingui/core/macro";
select(gender, {
offset: 1,
female: plural(numOfGuests, {
offset: 1,
0: t`${host} does not give a party.`,
1: t`${host} invites ${guest} to her party.`,
2: t`${host} invites ${guest} and one other person to her party.`,
other: t`${host} invites ${guest} and # other people to her party.`
}),
male: plural(value, {...}),
other: plural(value, {...}),
});
```
caution
All Core Macros cannot be used at the module level. They must be used within a component or function. See the [Macros](https://lingui.dev/ref/macro.md#using-macros) documentation for more information.
## See Also[](#see-also "Direct link to See Also")
* [Message Extraction Guide](https://lingui.dev/guides/message-extraction.md)
* [Pluralization Guide](https://lingui.dev/guides/plurals.md)
* [Dynamic Loading of Message Catalogs](https://lingui.dev/guides/dynamic-loading-catalogs.md)
* [Lingui CLI Reference](https://lingui.dev/ref/cli.md)
---
# React Apps Internationalization
In this tutorial, we'll learn how to add internationalization (i18n) to an existing React JS application. We'll focus on the most common patterns and best practices for using Lingui in React.
Example
If you're looking for a working solution, check out the [Examples](https://lingui.dev/examples.md) page. It contains several sample projects with the complete setup using Lingui and React.
It includes examples for *React with Vite and Babel*, *React with Vite and SWC*, and more.
## Installing Lingui[](#installing-lingui "Direct link to Installing Lingui")
1. Follow the [Installation and Setup](https://lingui.dev/installation.md) page for initial setup.
2. Install the [`@lingui/core`](https://lingui.dev/ref/core.md) and [`@lingui/react`](https://lingui.dev/ref/react.md) packages.
## Example Component[](#example-component "Direct link to Example Component")
We're going to translate the following one-page mailbox application:
src/index.js
```
import React from "react";
import ReactDOM from "react-dom/client";
import Inbox from "./Inbox";
const App = () => ;
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
);
```
src/Inbox.js
```
import React from "react";
export default function Inbox() {
const messages = [{}, {}];
const messagesCount = messages.length;
const lastLogin = new Date();
const markAsRead = () => {
alert("Marked as read.");
};
return (
{messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`}
);
}
```
This application is a simple mailbox with a header, a paragraph with a link and a button, another paragraph with a message count, and a footer with the last login date. We will use it as the basis for our tutorial.
## Setup[](#setup "Direct link to Setup")
We will start translating the `Inbox` component right away, but we need to do one more step to set up our application.
Components need to read information about current language and message catalogs from the [`i18n`](https://lingui.dev/ref/core.md#i18n) instance. Lingui uses the [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) to pass the `i18n` instance to your React components.
Let's add all required imports and wrap our app inside [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider):
src/index.js
```
import React from "react";
import ReactDOM from "react-dom/client";
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
import { messages } from "./locales/en/messages";
import Inbox from "./Inbox";
i18n.load("en", messages);
i18n.activate("en");
const App = () => (
);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
);
```
info
You might be wondering: how are we going to change the active language? That's what the [`I18n.load`](https://lingui.dev/ref/core.md#i18n.load) and [`i18n.activate`](https://lingui.dev/ref/core.md#i18n.activate) calls are for! However, we cannot change the language unless we have the translated message catalog. And to get the catalog, we first need to extract all messages from the source code.
## Introducing Internationalization[](#introducing-internationalization "Direct link to Introducing Internationalization")
Now we're finally going to *translate* our application. Actually, we're not going to *translate* from one language to another right now. Instead, we're going to *prepare* our app for translation. This process is called *internationalization*.
Let's start with the basics - static messages. These messages don't have any variables, HTML or components inside. Just some text:
```
Message Inbox
```
To make this heading translatable, simply wrap it in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro:
```
import { Trans } from "@lingui/react/macro";
Message Inbox
;
```
Using JSX Macros is the easiest way to translate your React components. It handles translations of messages, including variables and other React components.
### Macros vs. Components[](#macros-vs-components "Direct link to Macros vs. Components")
If you're wondering what [Macros](https://lingui.dev/ref/macro.md) are and the difference between macros and runtime components, here's a quick explanation.
In general, macros are executed at compile time and serve to transform the source code to make the message writing process easier. Under the hood, all JSX macros are transformed into the runtime component [`Trans`](https://lingui.dev/ref/react.md#trans) (imported from `@lingui/react`).
Below is a brief example demonstrating this transformation:
```
import { Trans } from "@lingui/react/macro";
Hello {name};
// ↓ ↓ ↓ ↓ ↓ ↓
import { Trans } from "@lingui/react";
;
```
As you can see, the [`Trans`](https://lingui.dev/ref/react.md#trans) runtime component gets `id` and `message` props with a message in [ICU MessageFormat](https://lingui.dev/guides/message-format.md) syntax. We could write it manually, but it's just easier and shorter to write JSX as we're used to and let macros generate the message for us.
Bundle Size Impact
Another advantage of using macros is that all non-essential properties are excluded from the production build. This results in a significant reduction in the size footprint for internationalization:
```
// NODE_ENV=production
import { Trans } from "@lingui/react";
;
```
### Extracting Messages[](#extracting-messages "Direct link to Extracting Messages")
Back to our project. It's nice to use JSX and let macros generate messages under the hood. Let's check that it actually works correctly.
All messages from the source code must be extracted into external message catalogs. Message catalogs are interchange files between developers and translators. We're going to have one file per language.
info
Refer to the [Message Extraction](https://lingui.dev/guides/message-extraction.md) guide for more information about various message extraction concepts and strategies.
Let's switch to the command line for a moment. Execute the [`extract`](https://lingui.dev/ref/cli.md#extract) CLI command. If everything is set up correctly, you should see the extracted message statistics in the output:
```
> lingui extract
Catalog statistics:
┌──────────┬─────────────┬─────────┐
│ Language │ Total count │ Missing │
├──────────┼─────────────┼─────────┤
│ cs │ 1 │ 1 │
│ en │ 1 │ 1 │
└──────────┴─────────────┴─────────┘
```
As a result, we have two new files in the `locales` directory: `en/messages.po` and `cs/messages.po`. These files contain extracted messages from the source code.
Let's take a look at the Czech message catalog:
src/locales/cs/messages.po
```
msgid ""
msgstr ""
"POT-Creation-Date: 2021-07-22 21:44+0900\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: @lingui/cli\n"
"Language: cs\n"
#: src/Inbox.js:12
msgid "Message Inbox"
msgstr ""
```
It contains the message we wrapped in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro. Let's add the Czech translation:
src/locales/cs/messages.po
```
#: src/Inbox.js:12
msgid "Message Inbox"
msgstr "Příchozí zprávy"
```
If we run the [`extract`](https://lingui.dev/ref/cli.md#extract) command again, we'll see that all the Czech messages have been translated:
```
> lingui extract
Catalog statistics:
┌──────────┬─────────────┬─────────┐
│ Language │ Total count │ Missing │
├──────────┼─────────────┼─────────┤
│ cs │ 1 │ 0 │
│ en │ 1 │ 1 │
└──────────┴─────────────┴─────────┘
```
That's great! So how do we load it into your application? Lingui introduces the concept of compiled message catalogs. Before we load messages into our application, we need to compile them.
Use the [`compile`](https://lingui.dev/ref/cli.md#compile) command to do this:
```
> lingui compile
Compiling message catalogs…
Done!
```
If you look inside the `locales/` directory, you'll see that there is a new file for each locale: `messages.js`. This file contains the compiled message catalog.
tip
If you use TypeScript, you can add the `--typescript` flag to the `compile` command to produce compiled message catalogs with TypeScript types.
Let's load this file into our app and set active language to `cs`:
src/index.js
```
import React from "react";
import ReactDOM from "react-dom/client";
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
import { messages as enMessages } from "./locales/en/messages";
import { messages as csMessages } from "./locales/cs/messages";
import Inbox from "./Inbox";
i18n.load({
en: enMessages,
cs: csMessages,
});
i18n.activate("cs");
const App = () => (
);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
);
```
When we run the app, we see the inbox header is translated into Czech.
tip
Alternatively, you can load catalogs dynamically using the [`@lingui/loader`](https://lingui.dev/ref/loader.md) or [`@lingui/vite-plugin`](https://lingui.dev/ref/vite-plugin.md) without the need to import compiled messages manually.
### Summary of Basic Workflow[](#summary-of-basic-workflow "Direct link to Summary of Basic Workflow")
Let's go through the workflow again:
1. Add an [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider), this component provides the active language and catalog(s) to other components.
2. Wrap messages in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro.
3. Run [`extract`](https://lingui.dev/ref/cli.md#extract) command to generate message catalogs.
4. Translate message catalogs (send them to translators usually).
5. Run [`compile`](https://lingui.dev/ref/cli.md#compile) to create runtime catalogs.
6. Load runtime catalog.
7. Profit! 🎉
It's not necessary to extract/translate messages one by one. This is usually done in batches. When you finish your work or PR, run [`extract`](https://lingui.dev/ref/cli.md#extract) to generate the latest message catalogs, and before building the application for production, run [`compile`](https://lingui.dev/ref/cli.md#compile).
## Formatting[](#formatting "Direct link to Formatting")
Let's move on to another paragraph in our project. The following paragraph has some variables, some HTML and components inside:
```
```
Although it looks complex, there's really nothing special here. Just wrap the content of the paragraph in [`Trans`](https://lingui.dev/ref/macro.md#trans) and let the macro do the magic:
```
```
Let's see how this message actually looks in the message catalog. Run the [`extract`](https://lingui.dev/ref/cli.md#extract) command and take a look at the message:
```
#: src/Inbox.js:20
msgid "See all <0>unread messages0> or <1>mark them1> as read."
msgstr ""
```
You may notice that components and html tags are replaced with indexed tags (`<0>`, `<1>`). This is a little extension to the ICU MessageFormat which allows rich-text formatting inside translations. Components and their props remain in the source code and don't scare our translators. Also, in case we change a `className`, we don't need to update our message catalogs.
### JSX to MessageFormat Transformations[](#jsx-to-messageformat-transformations "Direct link to JSX to MessageFormat Transformations")
At first glance, these transformations might seem somewhat unconventional; however, they are straightforward, intuitive, and align well with React principles. There is no need to focus on MessageFormat, as the library handles its creation for us. We can write our components as we typically would and simply wrap the text in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro.
Let's see some examples with MessageFormat equivalents:
```
Hello {name}
// Hello {name}
```
Any expressions are allowed, not just simple variables. The only difference is, only the variable name will be included in the extracted message:
* Any expression -> positional argument:
```
Hello {user.name}
// Hello {0}
```
* Object, arrays, function calls -> positional argument:
```
The random number is {Math.rand()}
// The random number is {0}
```
* Components might get tricky, but like we saw, it's really easy:
```
Read more.
// Read <0>more0>.
```
```
Dear Watson,
it's not exactly what I had in my mind.
// Dear Watson,<0/>it's not exactly what I had in my mind.
```
caution
Try to keep your messages simple and avoid complex expressions. During extraction, these expressions will be replaced by positional placeholders such as `{0}`, resulting in a lack of context for translators. When you can't avoid an expression, give it a name with the [`ph`](https://lingui.dev/ref/macro.md#ph) macro: `` t`Hello ${ph({ name: user.name })}` `` is extracted as `Hello {name}`. There is also a special rule in Lingui [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md) to catch these cases: [`no-expression-in-message`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-expression-in-message.md).
Similarly, to prevent numbered tag placeholders like `<0>` from depriving translators of context, use [named tag placeholders](https://lingui.dev/ref/conf.md#macrojsxplaceholderattribute) and enforce them with [`no-unnamed-tag-placeholders`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-unnamed-tag-placeholders.md).
See [Translator-friendly Messages](https://lingui.dev/guides/translator-friendly-messages.md) for the complete set of practices.
### Dates and Numbers[](#dates-and-numbers "Direct link to Dates and Numbers")
Take a look at the message in the footer of our component. It is a bit special because it contains a date:
```
```
Dates (as well as numbers) are formatted differently in different languages, but we don't have to do this manually. The heavy lifting is done by the [`Intl` object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl).
The `i18n` object can be accessed with the [`useLingui`](https://lingui.dev/ref/react.md#uselingui) hook:
src/Inbox.js
```
import { useLingui, Trans } from "@lingui/react/macro";
import { useMemo } from "react";
export default function Inbox() {
const { i18n } = useLingui();
const dateFormatter = useMemo(() => new Intl.DateTimeFormat(i18n.locale), [i18n.locale]);
return (
);
}
```
This will format the date using the conventional format for the active language. To format numbers, use `Intl.NumberFormat` in a similar way.
### Message ID[](#message-id "Direct link to Message ID")
At this point, we'll explain what the message ID is and how to set it manually. Translators work with *message catalogs*. No matter what format we use, it's just a mapping of a message ID to the translation.
Here's an example of a simple message catalog in **Czech** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Pondělí |
| Tuesday | Úterý |
| Wednesday | Středa |
... and the same catalog in **French** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Lundi |
| Tuesday | Mardi |
| Wednesday | Mercredi |
The message ID is *what all catalogs have in common* – "Lundi" and "Pondělí" represent the same message in different languages.
There are two approaches for creating a message ID:
* Automatically generated from message (e.g. `Monday`) and context, if available.
* Explicit message ID set by the developer (e.g. `days.monday`).
info
Refer to the [Explicit vs Generated IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md) guide for more information about the pros and cons of each approach.
## Plurals[](#plurals "Direct link to Plurals")
Let's take a closer look at the following code in our component:
```
{messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`}
```
This message is a bit special, because it depends on the value of the `messagesCount` variable. Most languages use different forms of words when describing quantities - this is called [pluralization](https://lingui.dev/guides/plurals.md).
What's tricky is that different languages use different number of plural forms. For example, English has only two forms - singular and plural - as we can see in the example above. However, Czech language has three plural forms. Some languages have up to 6 plural forms and some don't have plurals at all!
info
Lingui uses `Intl.PluralRules` which is supported in [every modern browser](https://caniuse.com/intl-pluralrules) and can be polyfilled for older. So you don't need to setup anything special.
### English Plural Rules[](#english-plural-rules "Direct link to English Plural Rules")
How do we know which plural form we should use? It's very simple: we, as developers, only need to know plural forms of the language we use in our source. Our component is written in English, so looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en) we'll need just two forms:
`one`
> Singular form
`other`
> Plural form
We don't need to select these forms manually. We'll use [`Plural`](https://lingui.dev/ref/macro.md#plural-1) component, which takes a `value` prop and based on the active language, selects the right plural form:
```
import { Plural } from "@lingui/react/macro";
;
```
This component will render `There's 1 message in your inbox` when `messageCount = 1` and `There are # messages in your inbox` for any other values of `messageCount`. `#` is a placeholder, which is replaced with `value`.
Let's run the [`extract`](https://lingui.dev/ref/cli.md#extract) command to see the extracted message:
```
{messagesCount, plural,
one {There's # message in your inbox}
other {There are # messages in your inbox}
}
```
In the catalog, you'll see the message in a single line. Here we have wrapped it to make it more readable.
### Beware of Zeroes\
Just a short detour, because it's a common misunderstanding. You may wonder why the following code doesn't work as expected:
```
```
This component will render `There are 0 messages in your inbox` for `messagesCount = 0`. Why so? Because English doesn't have `zero` plural form. Looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en), it's:
| N | Form |
| - | --------------------- |
| 0 | other |
| 1 | one |
| n | other (anything else) |
However, decimal numbers (even `1.0`) always use the `other` form:
```
There are 0.0 messages in your inbox.
```
### Exact Forms[](#exact-forms "Direct link to Exact Forms")
Going back to our example, what if we specifically want to display `There are no messages` when `messagesCount = 0`? This is where exact forms come in handy:
```
```
tip
MessageFormat allows exact forms, like `=0`. However, React props can't start with `=` and can't be numbers either, so we need to write `_N` instead of `=0`.
It works with any number, allowing for extensive customization as follows:
```
```
Exact matches always take precedence over plural forms.
### Variables and Components[](#variables-and-components "Direct link to Variables and Components")
Let's go back to our original pluralized message:
```
```
To include variables or components within messages, simply wrap them in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro or use template literals (for example, with a variable `name`):
```
There are # messages in your inbox, {name}
}
/>
```
Nested macros, components, variables, and expressions are all supported, providing the flexibility needed for any use case.
## Internationalization Outside of React[](#internationalization-outside-of-react "Direct link to Internationalization Outside of React")
So far, we have learned how to translate strings within a JSX element. However, what if we need to translate content that is outside JSX or pass a translation as a prop to another component?
In our example, we have the following code:
```
const markAsRead = () => {
alert("Marked as read.");
};
```
To translate it, we will use the [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macro hook:
```
import { useLingui } from "@lingui/react/macro";
const { t } = useLingui();
const markAsRead = () => {
alert(t`Marked as read.`);
};
```
Now the `Marked as read.` message would be picked up by the extractor, and available for translation in the catalog.
You could also pass variables and use any other macro in the message:
```
const { t } = useLingui();
const markAsRead = () => {
const userName = "User1234";
alert(t`Hello ${userName}, your messages marked as read!`);
};
```
tip
You can also use this approach to translate element attributes, such as `alt` in an `img` tag:
```
import { useLingui } from "@lingui/react/macro";
export default function ImageWithCaption() {
const { t } = useLingui();
return ;
}
```
caution
All Core Macros cannot be used at the module level. They must be used within a component or function. See the [Macros](https://lingui.dev/ref/macro.md#using-macros) documentation for more information.
## Review[](#review "Direct link to Review")
After all modifications, the final i18n-ready component looks like this:
src/Inbox.js
```
import React, { useMemo } from "react";
import { Trans, Plural, useLingui } from "@lingui/react/macro";
export default function Inbox() {
const { i18n, t } = useLingui();
const messages = [{}, {}];
const messagesCount = messages.length;
const lastLogin = new Date();
const markAsRead = () => {
alert(t`Marked as read.`);
};
const dateFormatter = useMemo(() => new Intl.DateTimeFormat(i18n.locale), [i18n.locale]);
return (
);
}
```
That's it for this tutorial! For more details, see the reference documentation or check out additional tutorials. Happy Internationalizing!
## See Also[](#see-also "Direct link to See Also")
* [Next.js App Router i18n Tutorial](https://lingui.dev/tutorials/react-rsc.md)
* [React Native i18n Tutorial](https://lingui.dev/tutorials/react-native.md)
* [`@lingui/react` Reference](https://lingui.dev/ref/react.md)
---
# React Native Apps Internationalization
In this tutorial, we'll learn how to add internationalization to an existing application in React Native.
The React Native tutorial is similar to the one for [React](https://lingui.dev/tutorials/react.md) and we highly recommend you read that one first because it goes into greater detail on many topics. Here, we will only cover parts that are relevant for React Native.
Example
If you're looking for a working solution, check out the [React Native example](https://github.com/lingui/js-lingui/tree/main/examples/react-native). This example application shows a complete setup using Lingui and React Native.
This tutorial assumes you use Lingui >= 5.0 and React Native >=0.76 or Expo >=52, with the Hermes JavaScript Engine.
`@lingui/core` depends on several APIs exposed by the [`Intl` object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl). Support of the `Intl` object can vary across React Native and OS versions. If some `Intl` feature is not supported by your runtime, you can [polyfill it](#polyfilling-intl-apis).
## Installing Lingui[](#installing-lingui "Direct link to Installing Lingui")
1. Follow the [Installation and Setup](https://lingui.dev/installation.md?transpiler=babel) page for initial setup (for Babel).
2. Install the [`@lingui/core`](https://lingui.dev/ref/core.md) and [`@lingui/react`](https://lingui.dev/ref/react.md) packages.
3. *(optional)* Install and configure the [`@lingui/metro-transformer`](https://lingui.dev/ref/metro-transformer.md) package that enables Metro to compile `.po` files on the fly.
Warning
With the dependencies installed and set up, before running your app, please clear your Metro bundler cache with `npx expo start -c` or `npx react-native start --reset-cache` (if you do not use Expo).
## Polyfilling Intl APIs[](#polyfilling-intl-apis "Direct link to Polyfilling Intl APIs")
React Native's JS engine may not support all `Intl` features out of the box. As of 08/2024, we need to polyfill [`Intl.Locale`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) using [`@formatjs/intl-locale`](https://formatjs.github.io/docs/polyfills/intl-locale/) and [`Intl.PluralRules`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules) using [`@formatjs/intl-pluralrules`](https://formatjs.github.io/docs/polyfills/intl-pluralrules/). Please note that importing the `Intl` polyfills can significantly increase the amount of JS that needs to be `require`d by your app. At the same time, modern i18n libraries rely on its presence.
Follow the polyfill installation instructions before proceeding further. Import polyfills from `/polyfill-force` to avoid [slow initialization time on low-end devices](https://github.com/formatjs/formatjs/issues/4463).
## Example Component[](#example-component "Direct link to Example Component")
We're going to translate the following contrived example:
```
import React from "react";
import { StyleSheet, Text, View, Alert, SafeAreaView, Button } from "react-native";
export const AppRoot = () => {
const [messages, setMessages] = useState([]);
const markAllAsRead = () => {
Alert.alert("", "Do you want to set all your messages as read?", [
{
text: "OK",
onPress: () => {
setMessages([]);
},
},
]);
};
return (
{
setMessages((msgs) => msgs.concat([`message # ${msgs.length + 1}`]));
}}
/>
);
};
const Inbox = ({ messages, markAsRead }) => {
const messagesCount = messages.length;
return (
Message Inbox
{messagesCount === 1
? `There's {messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`}
{/* additional code for adding messages, etc.*/}
);
};
```
As you can see, it's a simple mailbox application with only one screen.
## Internationalization in React (Native)[](#internationalization-in-react-native "Direct link to Internationalization in React (Native)")
TL;DR
There are several ways to render translations: You may use the [`Trans`](https://lingui.dev/ref/react.md#trans) component or the [`useLingui`](https://lingui.dev/ref/react.md#uselingui) hook together with the [`t`](https://lingui.dev/ref/macro.md#t) or [`msg`](https://lingui.dev/ref/macro.md#definemessage) macros. When you change the active locale or load new messages, all components that consume the Lingui context provided by [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) will re-render, making sure the UI shows the correct translations.
Not surprisingly, this part isn't too different from the [React tutorial](https://lingui.dev/tutorials/react.md).
First, we need to wrap our app with [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) and then we can use the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro to translate the screen heading:
```
import { I18nProvider, TransRenderProps } from "@lingui/react";
import { Trans } from "@lingui/react/macro";
import { i18n } from "@lingui/core";
import { Text } from "react-native";
i18n.loadAndActivate({ locale: "en", messages });
const DefaultComponent = (props: TransRenderProps) => {
return {props.children};
};
// later in the React element tree:
Message Inbox
```
Hint
We're importing the default `i18n` object from `@lingui/core`. Read more about the `i18n` object in the [reference](https://lingui.dev/ref/core.md).
Translating the heading is done. Now, let's translate the `title` prop in the `` element. In this case, `Button` expects to receive a `string`, so we cannot use the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro here!
The solution is to use the `t` macro which we can obtain from the `useLingui` hook. We use it like this to get a translated string:
```
import { useLingui } from '@lingui/react/macro';
const { t } = useLingui();
...
```
Under the hood, [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) takes the instance of the `i18n` object and passes it to `Trans` components through React context. `I18nProvider` will update the context value (which then rerenders components that consume the provided context value) when locale or message catalogs are updated.
The `Trans` component uses the `i18n` instance to get the translations from it. If we cannot use `Trans`, we can use the `useLingui` hook to get hold of the `i18n` instance ourselves and get the translations from there.
The interplay of `I18nProvider` and `useLingui` is shown in the following simplified example:
```
import { I18nProvider } from "@lingui/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { i18n } from "@lingui/core";
;
//...
const Inbox = ({ markAsRead }) => {
const { t } = useLingui();
return (
Message Inbox
);
};
```
## Internationalization Outside of React[](#internationalization-outside-of-react "Direct link to Internationalization Outside of React")
Until now, we have covered the [`Trans`](https://lingui.dev/ref/react.md#trans) macro and the [`useLingui`](https://lingui.dev/ref/react.md#uselingui) hook. Using them will make sure our components are always in sync with the currently active locale and message catalog.
However, you may want to show localized strings outside of React, for example when you want to show an Alert from some business logic code.
In that case you'll also need access to the `i18n` object, but you don't need to pass it around from some React component. By default, Lingui uses an `i18n` object instance that you can import as follows:
```
import { i18n } from "@lingui/core";
```
This instance is the source of truth for the active locale. For string constants that will be translated at runtime, use the [`msg`](https://lingui.dev/ref/macro.md#definemessage) macro as follows:
```
const deleteTitle = msg`Are you sure to delete this?`
...
const showDeleteConfirmation = () => {
Alert.alert(i18n.t(deleteTitle))
}
```
## Changing the Active Locale[](#changing-the-active-locale "Direct link to Changing the Active Locale")
The last remaining piece of the puzzle is changing the active locale. The `i18n` object exposes [`i18n.loadAndActivate()`](https://lingui.dev/ref/core.md#i18n.loadAndActivate) for that. Call the method and the [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) will re-render the translations. It all becomes clear when you take a look at the [final code](https://github.com/lingui/js-lingui/tree/main/examples/react-native/src/MainScreen.tsx#L29).
However, we don't recommend that you change the locale like this in mobile apps, as it can cause conflicts in how your app ui is localized. This is further [explained here](https://www.youtube.com/live/uLicTDG5hSs?feature=share\&t=9088).
## Choosing the Default Locale[](#choosing-the-default-locale "Direct link to Choosing the Default Locale")
Lingui does not ship with functionality that would allow you to determine the best locale you should activate by default.
Instead, please refer to [Expo localization](https://docs.expo.dev/versions/latest/sdk/localization/#localizationgetlocales) or [react-native-localize](https://github.com/zoontek/react-native-localize#getlocales). Both packages will provide you with information about the locales that the user prefers. Combining that information with the locales that your app supports will give you the locale you should use by default.
## Rendering and Styling of Translations[](#rendering-and-styling-of-translations "Direct link to Rendering and Styling of Translations")
As described in the [reference](https://lingui.dev/ref/react.md#rendering-translations), by default, translation components render translation as text without a wrapping tag. In React Native though, all text must be wrapped in the `Text` component. This means we would need to use the [`Trans`](https://lingui.dev/ref/macro.md#trans) component like this:
```
Message Inbox
```
You'll surely agree the `Text` component looks a little redundant. That's why the [`I18nProvider`](https://lingui.dev/ref/react.md#i18nprovider) component accepts a `defaultComponent` prop. Just supply the `Text` component as the `defaultComponent` prop and the previous example can be simplified to:
```
Message Inbox
```
Alternatively, you may override the default locally on the i18n components, using the `render` or `component` props, as documented in the [reference](https://lingui.dev/ref/react.md#rendering-translations). Use them to apply styling to the rendered string.
## Nesting Components[](#nesting-components "Direct link to Nesting Components")
The [`Trans`](https://lingui.dev/ref/macro.md#trans) macro and `Text` component may be nested, for example to achieve the effect shown in the picture. This is thanks to how React Native [handles nested text](https://facebook.github.io/react-native/docs/text#nested-text).

This can be achieved by the following code:
```
Concert of Green Day tonight!
```
The extracted string for translation will look like this:
`"<0><1>Concert of 1><2>Green Day2><3> tonight!3>0>"`
The important point here is that the sentence isn't broken into pieces but remains together - that will allow the translator to deliver a quality result.
## See Also[](#see-also "Direct link to See Also")
* [React i18n Tutorial](https://lingui.dev/tutorials/react.md)
* [Message Extraction Guide](https://lingui.dev/guides/message-extraction.md)
* [`@lingui/react` Reference](https://lingui.dev/ref/react.md)
* [Lingui CLI Reference](https://lingui.dev/ref/cli.md)
* [Localizing React Native apps talk from React Native EU 2022](https://www.youtube.com/live/uLicTDG5hSs?feature=share\&t=7512)
***
This guide originally authored and contributed in full by [Vojtech Novak](https://twitter.com/vonovak).
---
# Next.js App Router i18n with React Server Components
Lingui provides support for React Server Components (RSC) as of v4.10.0. In this tutorial, we'll learn how to add internationalization to an application with the Next.js [App Router](https://nextjs.org/docs/app). However, the same principles are applicable to any RSC-based solution.
Example
There's a working example available [here](https://github.com/lingui/js-lingui/tree/main/examples/nextjs-swc). We will make references to the important parts of it throughout the tutorial. The example is more complete than this tutorial.
The example uses both Pages Router and App Router, so you can see how to use Lingui with both in [this commit](https://github.com/lingui/js-lingui/pull/1944/commits/100fc74abb49cff677f4b1cac1dfd5da60262b67).
Before going further, please follow the [Installation and Setup](https://lingui.dev/installation.md?transpiler=swc) instructions (for SWC or Babel depending on which you use - most likely it's SWC). You may also need to configure your `tsconfig.json` according to [this visual guide](https://twitter.com/mattpocockuk/status/1724462050288587123). This is so that TypeScript understands the values exported from `@lingui/react` package.
### Adding i18n Support to Next.js[](#adding-i18n-support-to-nextjs "Direct link to Adding i18n Support to Next.js")
Firstly, your Next.js app needs to be ready for routing and rendering of content in multiple languages. This is done through the proxy, called middleware before Next.js 16 (see the [example app's proxy](https://github.com/lingui/js-lingui/blob/main/examples/nextjs-swc/src/proxy.ts)). Please read the [official Next.js docs](https://nextjs.org/docs/app/guides/internationalization) for more information.
After configuring the proxy, make sure your page and route files are moved from `app` to `app/[lang]` folder (example: `app/[lang]/layout.tsx`). This enables the Next.js router to dynamically handle different locales in the route. Because `[lang]` sits above the root layout, it's a root parameter: since Next.js 16.3, any Server Component can read it with [`next/root-params`](https://nextjs.org/docs/app/api-reference/functions/next-root-params), without passing `params` down from layouts and pages.
### Next.js Config[](#nextjs-config "Direct link to Next.js Config")
Secondly, add the `swc-plugin` to the Next.js config, so that you can use [Lingui Macros](https://lingui.dev/ref/macro.md).
next.config.mjs
```
import { linguiMacroSwcPlugin } from "@lingui/swc-plugin/options";
/** @type {import('next').NextConfig} */
const nextConfig = {
// to use Lingui macros
experimental: {
swcPlugins: [linguiMacroSwcPlugin()],
},
};
export default nextConfig;
```
### Setup with Server Components[](#setup-with-server-components "Direct link to Setup with Server Components")
With Lingui, the experience of localizing React is the same in client and server components: `Trans` and `useLingui` can be used identically in both worlds, even though internally there are two implementations.
Under the hood
Translation strings, one way or another, are obtained from an [I18n](https://lingui.dev/ref/core.md) object instance. In client components, this instance is passed around using React context. Because context is not available in Server components, instead [`cache`](https://react.dev/reference/react/cache) is used to maintain an I18n instance for each request.
To make Lingui work in both server and client components, we need to take the `lang` of the current request and create a corresponding instance of the I18n object. We then make it available to the components in our app. This is a 2-step process:
1. given `lang`, take an I18n instance and store it in the [`cache`](https://react.dev/reference/react/cache) so it can be used server-side
2. given `lang`, take an I18n instance and make it available to client components via `I18nProvider`
Step (1) fits in a small helper. It reads `lang` with `next/root-params`, so it doesn't need any arguments:
src/initLingui.ts
```
import { lang } from "next/root-params";
import { setI18n } from "@lingui/react/server";
import { getI18nInstance } from "./appRouterI18n";
export async function initLingui() {
const i18n = getI18nInstance(await lang()); // get a ready-made i18n instance for the current locale
setI18n(i18n); // make it available server-side for the current request
return i18n;
}
```
The root layout calls it, and so does `generateMetadata`:
src/app/\[lang]/layout.tsx
```
import { msg } from "@lingui/core/macro";
import { initLingui } from "../../initLingui";
import { LinguiClientProvider } from "./LinguiClientProvider";
export async function generateMetadata() {
const i18n = await initLingui();
return {
title: i18n._(msg`Translation Demo`),
};
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const i18n = await initLingui();
return (
{children}
);
}
```
Next.js older than 16.3
`next/root-params` isn't available before Next.js 16.3. Take `lang` from the `params` prop that Next.js passes to every layout and page, and pass it to the helper instead:
```
export function initLingui(lang: string) {
const i18n = getI18nInstance(lang);
setI18n(i18n);
return i18n;
}
type Props = {
params: Promise<{ lang: string }>;
children: React.ReactNode;
};
export default async function RootLayout({ params, children }: Props) {
const { lang } = await params;
const i18n = initLingui(lang);
// ...render the same tree as above
}
```
In Next.js 14 and older, `params` is a plain object rather than a promise.
caution
Root parameter getters such as `lang()` only work in Server Components and the server-side code they call. They aren't available in Client Components, Server Actions, or Route Handlers: pass the locale explicitly there, for example as an argument from the component that calls the Server Action.
Inside a [`"use cache"`](https://nextjs.org/docs/app/api-reference/directives/use-cache) function, Next.js adds the root parameters you read to the cache key, so `getI18nInstance(await lang())` gives you one cache entry per locale. Calling `lang()` inside `unstable_cache` throws an error.
Step (2) is implemented in `LinguiClientProvider`, which is a client component:
LinguiClientProvider.tsx
```
"use client";
import { I18nProvider } from "@lingui/react";
import { type Messages, setupI18n } from "@lingui/core";
import { useState } from "react";
export function LinguiClientProvider({
children,
initialLocale,
initialMessages,
}: {
children: React.ReactNode;
initialLocale: string;
initialMessages: Messages;
}) {
const [i18n] = useState(() => {
return setupI18n({
locale: initialLocale,
messages: { [initialLocale]: initialMessages },
});
});
return {children};
}
```
tip
Why are we not passing the I18n instance directly from `RootLayout` to the client via `LinguiClientProvider`? It's because the I18n object isn't serializable, and cannot be passed from server to client.
Lastly, there's the `appRouterI18n.ts` file, which is only executed on server and holds one instance of I18n object for each locale of our application. See [here](https://github.com/lingui/js-lingui/blob/main/examples/nextjs-swc/src/appRouterI18n.ts) how it's implemented in the example app.
### Rendering Translations in Server and Client Components[](#rendering-translations-in-server-and-client-components "Direct link to Rendering Translations in Server and Client Components")
Below you can see an example of a React component. This component can be rendered **both with RSC and on client**. This is great if you're migrating a Lingui-based project from pages router to App Router because you can keep the same components working in both worlds.
In fact, if you swapped the html tags for their more universal alternatives, this component could also be used in React Native.
app/\[lang]/components/SomeComponent.tsx
```
import { Trans, useLingui } from "@lingui/react/macro";
export function SomeComponent() {
const { t } = useLingui();
return (
Some Item
{t`Other Item`}
);
}
```
As you may recall, hooks are not supported in RSC, so you might be surprised that this works. Under RSC, `useLingui` is actually not a hook but a simple function call which reads from the React `cache` mentioned above.
The [RSC implementation](https://github.com/lingui/js-lingui/blob/ec49d0cc53dbc4f9e0f92f0edcdf59f3e5c1de1f/packages/react/src/index-rsc.ts#L12) of `useLingui` uses `getI18n`, which is another way to obtain the I18n instance on the server.
### Pages, Layouts and Lingui[](#pages-layouts-and-lingui "Direct link to Pages, Layouts and Lingui")
There's one last caveat: in a real-world app, you will need to localize many pages, and layouts. Because of the way the App Router is designed, the `setI18n` call needs to happen not only in layouts, but also in pages. Read more in:
* [Why do nested layouts/pages render before their parent layouts?](https://github.com/vercel/next.js/discussions/53026)
* [On navigation, layouts preserve state and do not re-render](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#layouts)
`next/root-params` doesn't change this. Lingui's server-side `Trans` and `useLingui` read the I18n instance synchronously from the React `cache`, so it has to be set before they render, in every page and layout. What root params remove is the need to thread `params` through each of them: the call becomes a one-liner without arguments.
src/app/\[lang]/some-page/page.tsx
```
import { initLingui } from "../../../initLingui";
import { SomeComponent } from "../components/SomeComponent";
export default async function Page() {
await initLingui();
return ;
}
```
See [`initLingui.tsx`](https://github.com/lingui/js-lingui/blob/main/examples/nextjs-swc/src/initLingui.tsx) in the example app.
### Changing the Active Language[](#changing-the-active-language "Direct link to Changing the Active Language")
Most likely, your users will not need to change the language of the application because it will render in their preferred language (obtained from the `accept-language` header in the [proxy](https://github.com/lingui/js-lingui/blob/main/examples/nextjs-swc/src/proxy.ts)), or with a fallback.
To change language, redirect users to a page with the new locale in the url. We do not recommend [dynamic](https://lingui.dev/guides/dynamic-loading-catalogs.md) switching because server-rendered locale-dependent content would become stale.
### Static Rendering Pitfall[](#static-rendering-pitfall "Direct link to Static Rendering Pitfall")
Next.js can use [static rendering](https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default) where it renders your pages only once at build time and then serves them to all users.
To ensure static rendering takes into account the supported locales, implement [generateStaticParams](https://nextjs.org/docs/app/api-reference/functions/generate-static-params) which will build the content for all locales.
It's important that you do not create any locale-dependent strings at a place in the app where locale may not be initialized correctly at build time. This could result in the content being generated only for one locale, and for this reason we do not recommend using the global i18n object in such scenarios. For example:
```
import { i18n } from "@lingui/core";
import { t } from "@lingui/core/macro";
// 😰 if this code runs at build time, it'll always be in the locale
// which the imported global i18n object had at that time
const immutableGreeting = t(i18n)`Hello World`;
// ✅ this component will be statically rendered for each locale
// (specified with `generateStaticParams`)
export default function SomePage() {
return (
<>
Hello world {/* this is fine */}
>
);
}
```
Read more about [Lazy Translation](https://lingui.dev/guides/lazy-translations.md) to see how to handle translation defined on the module level.
## See Also[](#see-also "Direct link to See Also")
* [React i18n Tutorial](https://lingui.dev/tutorials/react.md)
* [`@lingui/react` Reference](https://lingui.dev/ref/react.md)
---
# Solid Apps Internationalization
In this tutorial, we'll learn how to add internationalization (i18n) to an existing SolidJS application. We'll focus on the most common patterns and best practices for using Lingui in Solid.
Example
If you're looking for a working solution, check out the [Examples](https://lingui.dev/examples.md) page. It contains sample projects with the complete setup using Lingui and Solid.
It includes an example for *Solid with Vite*.
## Installing Lingui[](#installing-lingui "Direct link to Installing Lingui")
1. Follow the [Installation and Setup](https://lingui.dev/installation.md) page for initial setup.
2. Install the [`@lingui/core`](https://lingui.dev/ref/core.md) and [`@lingui/solid`](https://lingui.dev/ref/solid.md) packages.
## Example Component[](#example-component "Direct link to Example Component")
We're going to translate the following one-page mailbox application:
src/index.js
```
import { render } from "solid-js/web";
import Inbox from "./Inbox";
const App = () => ;
render(() => , document.getElementById("root")!);
```
src/Inbox.js
```
export default function Inbox() {
const messages = [{}, {}];
const messagesCount = messages.length;
const lastLogin = new Date();
const markAsRead = () => {
alert("Marked as read.");
};
return (
{messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`}
);
}
```
This application is a simple mailbox with a header, a paragraph with a link and a button, another paragraph with a message count, and a footer with the last login date. We will use it as the basis for our tutorial.
## Configure Lingui for Solid[](#configure-lingui-for-solid "Direct link to Configure Lingui for Solid")
We recommend using `defineConfig` from `@lingui/solid/config` to create the configuration. It provides all required options for you.
lingui.config.ts
```
import { defineConfig } from "@lingui/solid/config";
export default defineConfig({
locales: ["en", "cs"],
sourceLocale: "en",
catalogs: [
{
path: "src/locales/{locale}/messages",
include: ["src"],
},
],
});
```
This is equivalent to:
lingui.config.ts
```
export default {
locales: ["en", "cs"],
sourceLocale: "en",
catalogs: [
{
path: "src/locales/{locale}/messages",
include: ["src"],
},
],
macro: {
jsxPackage: ["@lingui/solid/macro"],
jsxRuntime: "solid",
},
runtimeConfigModule: {
Trans: ["@lingui/solid", "Trans"],
useLingui: ["@lingui/solid", "useLingui"],
},
};
```
## Configure Vite[](#configure-vite "Direct link to Configure Vite")
Setup Lingui in `vite.config.ts`:
vite.config.ts
```
import { defineConfig } from "vite";
import solid from "vite-plugin-solid";
import { lingui } from "@lingui/vite-plugin";
export default defineConfig({
plugins: [
solid({
babel: {
plugins: ["@lingui/babel-plugin-lingui-macro"],
},
}),
lingui(),
],
});
```
tip
You can transform Lingui macros with the faster [native macro transform](https://lingui.dev/ref/vite-plugin.md#native-macro-transform) instead. Remove `@lingui/babel-plugin-lingui-macro` from the `solid()` options and place `lingui()` before `solid()`, so macros are transformed before Solid compiles JSX:
vite.config.ts
```
export default defineConfig({
plugins: [lingui({ macroTransform: true }), solid()],
});
```
## Setup[](#setup "Direct link to Setup")
We will start translating the `Inbox` component right away, but we need to do one more step to set up our application.
Components need to read information about current language and message catalogs from the [`i18n`](https://lingui.dev/ref/core.md#i18n) instance. Lingui uses the [`I18nProvider`](https://lingui.dev/ref/solid.md#i18nprovider) to pass the `i18n` instance to your Solid components.
Let's add all required imports and wrap our app inside [`I18nProvider`](https://lingui.dev/ref/solid.md#i18nprovider):
src/index.js
```
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/solid";
import { render } from "solid-js/web";
import { messages } from "./locales/en/messages";
import Inbox from "./Inbox";
i18n.load("en", messages);
i18n.activate("en");
const App = () => (
);
render(() => , document.getElementById("root")!);
```
info
You might be wondering: how are we going to change the active language? That's what the [`I18n.load`](https://lingui.dev/ref/core.md#i18n.load) and [`i18n.activate`](https://lingui.dev/ref/core.md#i18n.activate) calls are for! However, we cannot change the language unless we have the translated message catalog. And to get the catalog, we first need to extract all messages from the source code.
## Introducing Internationalization[](#introducing-internationalization "Direct link to Introducing Internationalization")
Now we're finally going to *translate* our application. Actually, we're not going to *translate* from one language to another right now. Instead, we're going to *prepare* our app for translation. This process is called *internationalization*.
Let's start with the basics - static messages. These messages don't have any variables, HTML or components inside. Just some text:
```
Message Inbox
```
To make this heading translatable, simply wrap it in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro:
```
import { Trans } from "@lingui/solid/macro";
Message Inbox
;
```
Using JSX Macros is the easiest way to translate your Solid components. It handles translations of messages, including variables and other Solid components.
### Macros vs. Components[](#macros-vs-components "Direct link to Macros vs. Components")
If you're wondering what [Macros](https://lingui.dev/ref/macro.md) are and the difference between macros and runtime components, here's a quick explanation.
In general, macros are executed at compile time and serve to transform the source code to make the message writing process easier. Under the hood, all JSX macros are transformed into the runtime component [`Trans`](https://lingui.dev/ref/solid.md#trans) (imported from `@lingui/solid`).
Below is a brief example demonstrating this transformation:
```
import { Trans } from "@lingui/solid/macro";
Hello {name};
// ↓ ↓ ↓ ↓ ↓ ↓
import { Trans } from "@lingui/solid";
;
```
As you can see, the [`Trans`](https://lingui.dev/ref/solid.md#trans) runtime component gets `id` and `message` props with a message in [ICU MessageFormat](https://lingui.dev/guides/message-format.md) syntax. We could write it manually, but it's just easier and shorter to write JSX as we're used to and let macros generate the message for us.
Bundle Size Impact
Another advantage of using macros is that all non-essential properties are excluded from the production build. This results in a significant reduction in the size footprint for internationalization:
```
// NODE_ENV=production
import { Trans } from "@lingui/solid";
;
```
### Extracting Messages[](#extracting-messages "Direct link to Extracting Messages")
Back to our project. It's nice to use JSX and let macros generate messages under the hood. Let's check that it actually works correctly.
All messages from the source code must be extracted into external message catalogs. Message catalogs are interchange files between developers and translators. We're going to have one file per language.
info
Refer to the [Message Extraction](https://lingui.dev/guides/message-extraction.md) guide for more information about various message extraction concepts and strategies.
Let's switch to the command line for a moment. Execute the [`extract`](https://lingui.dev/ref/cli.md#extract) CLI command. If everything is set up correctly, you should see the extracted message statistics in the output:
```
> lingui extract
Catalog statistics:
┌──────────┬─────────────┬─────────┐
│ Language │ Total count │ Missing │
├──────────┼─────────────┼─────────┤
│ cs │ 1 │ 1 │
│ en │ 1 │ 1 │
└──────────┴─────────────┴─────────┘
```
As a result, we have two new files in the `locales` directory: `en/messages.po` and `cs/messages.po`. These files contain extracted messages from the source code.
Let's take a look at the Czech message catalog:
src/locales/cs/messages.po
```
msgid ""
msgstr ""
"POT-Creation-Date: 2021-07-22 21:44+0900\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: @lingui/cli\n"
"Language: cs\n"
#: src/Inbox.js:12
msgid "Message Inbox"
msgstr ""
```
It contains the message we wrapped in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro. Let's add the Czech translation:
src/locales/cs/messages.po
```
#: src/Inbox.js:12
msgid "Message Inbox"
msgstr "Příchozí zprávy"
```
If we run the [`extract`](https://lingui.dev/ref/cli.md#extract) command again, we'll see that all the Czech messages have been translated:
```
> lingui extract
Catalog statistics:
┌──────────┬─────────────┬─────────┐
│ Language │ Total count │ Missing │
├──────────┼─────────────┼─────────┤
│ cs │ 1 │ 0 │
│ en │ 1 │ 1 │
└──────────┴─────────────┴─────────┘
```
That's great! So how do we load it into your application? Lingui introduces the concept of compiled message catalogs. Before we load messages into our application, we need to compile them.
Use the [`compile`](https://lingui.dev/ref/cli.md#compile) command to do this:
```
> lingui compile
Compiling message catalogs…
Done!
```
If you look inside the `locales/` directory, you'll see that there is a new file for each locale: `messages.js`. This file contains the compiled message catalog.
tip
If you use TypeScript, you can add the `--typescript` flag to the `compile` command to produce compiled message catalogs with TypeScript types.
Let's load this file into our app and set active language to `cs`:
src/index.js
```
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/solid";
import { render } from "solid-js/web";
import { messages as enMessages } from "./locales/en/messages";
import { messages as csMessages } from "./locales/cs/messages";
import Inbox from "./Inbox";
i18n.load({
en: enMessages,
cs: csMessages,
});
i18n.activate("cs");
const App = () => (
);
render(() => , document.getElementById("root")!);
```
When we run the app, we see the inbox header is translated into Czech.
tip
Alternatively, you can load catalogs dynamically using the [`@lingui/loader`](https://lingui.dev/ref/loader.md) or [`@lingui/vite-plugin`](https://lingui.dev/ref/vite-plugin.md) without the need to import compiled messages manually.
### Summary of Basic Workflow[](#summary-of-basic-workflow "Direct link to Summary of Basic Workflow")
Let's go through the workflow again:
1. Add an [`I18nProvider`](https://lingui.dev/ref/solid.md#i18nprovider), this component provides the active language and catalog(s) to other components.
2. Wrap messages in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro.
3. Run [`extract`](https://lingui.dev/ref/cli.md#extract) command to generate message catalogs.
4. Translate message catalogs (send them to translators usually).
5. Run [`compile`](https://lingui.dev/ref/cli.md#compile) to create runtime catalogs.
6. Load runtime catalog.
7. Profit! 🎉
It's not necessary to extract/translate messages one by one. This is usually done in batches. When you finish your work or PR, run [`extract`](https://lingui.dev/ref/cli.md#extract) to generate the latest message catalogs, and before building the application for production, run [`compile`](https://lingui.dev/ref/cli.md#compile).
## Formatting[](#formatting "Direct link to Formatting")
Let's move on to another paragraph in our project. The following paragraph has some variables, some HTML and components inside:
```
```
Although it looks complex, there's really nothing special here. Just wrap the content of the paragraph in [`Trans`](https://lingui.dev/ref/macro.md#trans) and let the macro do the magic:
```
```
Let's see how this message actually looks in the message catalog. Run the [`extract`](https://lingui.dev/ref/cli.md#extract) command and take a look at the message:
```
#: src/Inbox.js:20
msgid "See all <0>unread messages0> or <1>mark them1> as read."
msgstr ""
```
You may notice that components and html tags are replaced with indexed tags (`<0>`, `<1>`). This is a little extension to the ICU MessageFormat which allows rich-text formatting inside translations. Components and their props remain in the source code and don't scare our translators. Also, in case we change a `class`, we don't need to update our message catalogs.
Solid JSX references
Solid JSX values are references. Don't store a JSX element in a variable and use it more than once in a message:
```
const docsLink = documentation;
Read {docsLink} or open {docsLink}.
;
```
The second use will move the same DOM node instead of rendering another copy. Use inline JSX or a component so Solid creates a new instance at each position:
```
const DocsLink = () => documentation;
Read or open .
;
```
### JSX to MessageFormat Transformations[](#jsx-to-messageformat-transformations "Direct link to JSX to MessageFormat Transformations")
At first glance, these transformations might seem somewhat unconventional; however, they are straightforward, intuitive, and align well with Solid principles. There is no need to focus on MessageFormat, as the library handles its creation for us. We can write our components as we typically would and simply wrap the text in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro.
Let's see some examples with MessageFormat equivalents:
```
Hello {name}
// Hello {name}
```
Any expressions are allowed, not just simple variables. The only difference is, only the variable name will be included in the extracted message:
* Any expression -> positional argument:
```
Hello {user.name}
// Hello {0}
```
* Object, arrays, function calls -> positional argument:
```
The random number is {Math.random()}
// The random number is {0}
```
* Components might get tricky, but like we saw, it's really easy:
```
Read more.
// Read <0>more0>.
```
```
Dear Watson,
it's not exactly what I had in my mind.
// Dear Watson,<0/>it's not exactly what I had in my mind.
```
caution
Try to keep your messages simple and avoid complex expressions. During extraction, these expressions will be replaced by positional placeholders such as `{0}`, resulting in a lack of context for translators. When you can't avoid an expression, give it a name with the [`ph`](https://lingui.dev/ref/macro.md#ph) macro: `` t`Hello ${ph({ name: user.name })}` `` is extracted as `Hello {name}`. There is also a special rule in Lingui [ESLint Plugin](https://lingui.dev/ref/eslint-plugin.md) to catch these cases: [`no-expression-in-message`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-expression-in-message.md).
Similarly, to prevent numbered tag placeholders like `<0>` from depriving translators of context, use [named tag placeholders](https://lingui.dev/ref/conf.md#macrojsxplaceholderattribute) and enforce them with [`no-unnamed-tag-placeholders`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-unnamed-tag-placeholders.md).
See [Translator-friendly Messages](https://lingui.dev/guides/translator-friendly-messages.md) for the complete set of practices.
### Dates and Numbers[](#dates-and-numbers "Direct link to Dates and Numbers")
Take a look at the message in the footer of our component. It is a bit special because it contains a date:
```
```
Dates (as well as numbers) are formatted differently in different languages, but we don't have to do this manually. The heavy lifting is done by the [`Intl` object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl).
The `i18n` object can be accessed with the [`useLingui`](https://lingui.dev/ref/solid.md#uselingui) hook:
src/Inbox.js
```
import { createMemo } from "solid-js";
import { Trans, useLingui } from "@lingui/solid/macro";
export default function Inbox() {
const { i18n } = useLingui();
const dateFormatter = createMemo(() => new Intl.DateTimeFormat(i18n().locale));
return (
);
}
```
This will format the date using the conventional format for the active language. To format numbers, use `Intl.NumberFormat` in a similar way.
### Message ID[](#message-id "Direct link to Message ID")
At this point, we'll explain what the message ID is and how to set it manually. Translators work with *message catalogs*. No matter what format we use, it's just a mapping of a message ID to the translation.
Here's an example of a simple message catalog in **Czech** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Pondělí |
| Tuesday | Úterý |
| Wednesday | Středa |
... and the same catalog in **French** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Lundi |
| Tuesday | Mardi |
| Wednesday | Mercredi |
The message ID is *what all catalogs have in common* – "Lundi" and "Pondělí" represent the same message in different languages.
There are two approaches for creating a message ID:
* Automatically generated from message (e.g. `Monday`) and context, if available.
* Explicit message ID set by the developer (e.g. `days.monday`).
info
Refer to the [Explicit vs Generated IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md) guide for more information about the pros and cons of each approach.
## Plurals[](#plurals "Direct link to Plurals")
Let's take a closer look at the following code in our component:
```
{messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`}
```
This message is a bit special, because it depends on the value of the `messagesCount` variable. Most languages use different forms of words when describing quantities - this is called [pluralization](https://lingui.dev/guides/plurals.md).
What's tricky is that different languages use different number of plural forms. For example, English has only two forms - singular and plural - as we can see in the example above. However, Czech language has three plural forms. Some languages have up to 6 plural forms and some don't have plurals at all!
info
Lingui uses `Intl.PluralRules` which is supported in [every modern browser](https://caniuse.com/intl-pluralrules) and can be polyfilled for older. So you don't need to setup anything special.
### English Plural Rules[](#english-plural-rules "Direct link to English Plural Rules")
How do we know which plural form we should use? It's very simple: we, as developers, only need to know plural forms of the language we use in our source. Our component is written in English, so looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en) we'll need just two forms:
`one`
> Singular form
`other`
> Plural form
We don't need to select these forms manually. We'll use [`Plural`](https://lingui.dev/ref/macro.md#plural-1) component, which takes a `value` prop and based on the active language, selects the right plural form:
```
import { Plural } from "@lingui/solid/macro";
;
```
This component will render `There's 1 message in your inbox` when `messagesCount = 1` and `There are # messages in your inbox` for any other values of `messagesCount`. `#` is a placeholder, which is replaced with `value`.
Let's run the [`extract`](https://lingui.dev/ref/cli.md#extract) command to see the extracted message:
```
{messagesCount, plural,
one {There's # message in your inbox}
other {There are # messages in your inbox}
}
```
In the catalog, you'll see the message in a single line. Here we have wrapped it to make it more readable.
### Beware of Zeroes\
Just a short detour, because it's a common misunderstanding. You may wonder why the following code doesn't work as expected:
```
```
This component will render `There are 0 messages in your inbox` for `messagesCount = 0`. Why so? Because English doesn't have `zero` plural form. Looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en), it's:
| N | Form |
| - | --------------------- |
| 0 | other |
| 1 | one |
| n | other (anything else) |
However, decimal numbers (even `1.0`) always use the `other` form:
```
There are 0.0 messages in your inbox.
```
### Exact Forms[](#exact-forms "Direct link to Exact Forms")
Going back to our example, what if we specifically want to display `There are no messages` when `messagesCount = 0`? This is where exact forms come in handy:
```
```
tip
MessageFormat allows exact forms, like `=0`. However, JSX props can't start with `=` and can't be numbers either, so we need to write `_N` instead of `=0`.
It works with any number, allowing for extensive customization as follows:
```
```
Exact matches always take precedence over plural forms.
### Variables and Components[](#variables-and-components "Direct link to Variables and Components")
Let's go back to our original pluralized message:
```
```
To include variables or components within messages, simply wrap them in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro or use template literals (for example, with a variable `name`):
```
There are # messages in your inbox, {name}
}
/>
```
Nested macros, components, variables, and expressions are all supported, providing the flexibility needed for any use case.
## Internationalization Outside of Solid[](#internationalization-outside-of-solid "Direct link to Internationalization Outside of Solid")
So far, we have learned how to translate strings within a JSX element. However, what if we need to translate content that is outside JSX or pass a translation as a prop to another component?
In our example, we have the following code:
```
const markAsRead = () => {
alert("Marked as read.");
};
```
To translate it, we will use the [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macro hook:
```
import { useLingui } from "@lingui/solid/macro";
const { t } = useLingui();
const markAsRead = () => {
alert(t`Marked as read.`);
};
```
Now the `Marked as read.` message would be picked up by the extractor, and available for translation in the catalog.
You could also pass variables and use any other macro in the message:
```
const { t } = useLingui();
const markAsRead = () => {
const userName = "User1234";
alert(t`Hello ${userName}, your messages marked as read!`);
};
```
tip
You can also use this approach to translate element attributes, such as `alt` in an `img` tag:
```
import { useLingui } from "@lingui/solid/macro";
export default function ImageWithCaption() {
const { t } = useLingui();
return ;
}
```
caution
All Core Macros cannot be used at the module level. They must be used within a component or function. See the [Macros](https://lingui.dev/ref/macro.md#using-macros) documentation for more information.
## Review[](#review "Direct link to Review")
After all modifications, the final i18n-ready component looks like this:
src/Inbox.js
```
import { createMemo } from "solid-js";
import { Trans, Plural, useLingui } from "@lingui/solid/macro";
export default function Inbox() {
const { i18n, t } = useLingui();
const messages = [{}, {}];
const messagesCount = messages.length;
const lastLogin = new Date();
const markAsRead = () => {
alert(t`Marked as read.`);
};
const dateFormatter = createMemo(() => new Intl.DateTimeFormat(i18n().locale));
return (
);
}
```
That's it for this tutorial! For more details, see the reference documentation or check out additional tutorials. Happy Internationalizing!
## See Also[](#see-also "Direct link to See Also")
* [`@lingui/solid` Reference](https://lingui.dev/ref/solid.md)
* [Examples](https://lingui.dev/examples.md)
---
# Vue Apps Internationalization
In this tutorial, we'll learn how to add internationalization (i18n) to an existing Vue 3 application. We'll focus on the most common patterns and best practices for using Lingui in Vue single-file components.
Example
If you're looking for a working solution, check out the [Examples](https://lingui.dev/examples.md) page. It contains sample projects with the complete setup using Lingui and Vue.
It includes an example for *Vue with Vite*.
## Installing Lingui[](#installing-lingui "Direct link to Installing Lingui")
1. Follow the [Installation and Setup](https://lingui.dev/installation.md) page for initial setup.
2. Install the [`@lingui/core`](https://lingui.dev/ref/core.md), [`@lingui/vue`](https://lingui.dev/ref/vue.md) and [`@lingui/extractor-vue`](https://lingui.dev/ref/extractor-vue.md) packages:
* npm
* Yarn
* pnpm
```
npm install --save @lingui/core @lingui/vue
npm install --save-dev @lingui/cli @lingui/vite-plugin @lingui/extractor-vue
```
```
yarn add @lingui/core @lingui/vue
yarn add --dev @lingui/cli @lingui/vite-plugin @lingui/extractor-vue
```
```
pnpm add @lingui/core @lingui/vue
pnpm add --save-dev @lingui/cli @lingui/vite-plugin @lingui/extractor-vue
```
## Example Component[](#example-component "Direct link to Example Component")
We're going to translate the following one-page mailbox application:
src/main.ts
```
import { createApp } from "vue";
import Inbox from "./Inbox.vue";
createApp(Inbox).mount("#app");
```
src/Inbox.vue
```
{{
messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`
}}
```
This application is a simple mailbox with a header, a paragraph with a link and a button, another paragraph with a message count, and a footer with the last login date. We will use it as the basis for our tutorial.
## Configure Lingui for Vue[](#configure-lingui-for-vue "Direct link to Configure Lingui for Vue")
We recommend using `defineConfig` from `@lingui/vue/config` to create the configuration. It provides all required options for you. Add the [Vue extractor](https://lingui.dev/ref/extractor-vue.md) so messages are extracted from `.vue` files:
lingui.config.ts
```
import { defineConfig } from "@lingui/vue/config";
import { createVueExtractor } from "@lingui/extractor-vue";
import babel from "@lingui/cli/api/extractors/babel";
export default defineConfig({
locales: ["en", "cs"],
sourceLocale: "en",
catalogs: [
{
path: "src/locales/{locale}/messages",
include: ["src"],
},
],
extractors: [babel, createVueExtractor()],
});
```
This is equivalent to:
lingui.config.ts
```
export default {
locales: ["en", "cs"],
sourceLocale: "en",
catalogs: [
{
path: "src/locales/{locale}/messages",
include: ["src"],
},
],
extractors: [babel, createVueExtractor()],
macro: {
jsxPackage: ["@lingui/vue/macro"],
jsxRuntime: "vue",
},
runtimeConfigModule: {
Trans: ["@lingui/vue", "Trans"],
useLingui: ["@lingui/vue", "useLingui"],
},
};
```
## Configure Vite[](#configure-vite "Direct link to Configure Vite")
Setup Lingui in `vite.config.ts`. The [`linguiVue`](https://lingui.dev/ref/vue.md#vite-integration) plugin teaches the Vue template compiler about Lingui macros and runs the Babel macro on `
```
src/main.ts
```
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");
```
tip
If you prefer a Vue plugin over a wrapper component, [`createLingui`](https://lingui.dev/ref/vue.md#createlingui) provides the same context to the whole application with `app.use(createLingui({ i18n }))`.
info
You might be wondering: how are we going to change the active language? That's what the [`I18n.load`](https://lingui.dev/ref/core.md#i18n.load) and [`i18n.activate`](https://lingui.dev/ref/core.md#i18n.activate) calls are for! However, we cannot change the language unless we have the translated message catalog. And to get the catalog, we first need to extract all messages from the source code.
## Introducing Internationalization[](#introducing-internationalization "Direct link to Introducing Internationalization")
Now we're finally going to *translate* our application. Actually, we're not going to *translate* from one language to another right now. Instead, we're going to *prepare* our app for translation. This process is called *internationalization*.
Let's start with the basics - static messages. These messages don't have any variables, HTML or components inside. Just some text:
```
Message Inbox
```
To make this heading translatable, simply wrap it in the [`Trans`](https://lingui.dev/ref/macro.md#trans) macro:
```
Message Inbox
```
Using the `Trans` macro in templates is the easiest way to translate your Vue components. It handles translations of messages, including variables and other elements.
### Macros vs. Components[](#macros-vs-components "Direct link to Macros vs. Components")
If you're wondering what [Macros](https://lingui.dev/ref/macro.md) are and the difference between macros and runtime components, here's a quick explanation.
In general, macros are executed at compile time and serve to transform the source code to make the message writing process easier. Vue templates are compiled by the Vue compiler, so `@lingui/vue` ships a [template transform](https://lingui.dev/ref/vue.md#template-transform) that plays the role of the macro there: it turns the message written inside `` into the props of the runtime [`Trans`](https://lingui.dev/ref/vue.md#trans) component, and the Babel macro points the `@lingui/vue/macro` import of `
```
When we run the app, we see the inbox header is translated into Czech.
tip
Alternatively, you can load catalogs dynamically using the [`@lingui/vite-plugin`](https://lingui.dev/ref/vite-plugin.md) without the need to import compiled messages manually.
### Summary of Basic Workflow[](#summary-of-basic-workflow "Direct link to Summary of Basic Workflow")
Let's go through the workflow again:
1. Add an [`I18nProvider`](https://lingui.dev/ref/vue.md#i18nprovider), this component provides the active language and catalog(s) to other components.
2. Wrap messages in the [`Trans`](https://lingui.dev/ref/vue.md#trans) component.
3. Run [`extract`](https://lingui.dev/ref/cli.md#extract) command to generate message catalogs.
4. Translate message catalogs (send them to translators usually).
5. Run [`compile`](https://lingui.dev/ref/cli.md#compile) to create runtime catalogs.
6. Load runtime catalog.
7. Profit! 🎉
It's not necessary to extract/translate messages one by one. This is usually done in batches. When you finish your work or PR, run [`extract`](https://lingui.dev/ref/cli.md#extract) to generate the latest message catalogs, and before building the application for production, run [`compile`](https://lingui.dev/ref/cli.md#compile).
## Formatting[](#formatting "Direct link to Formatting")
Let's move on to another paragraph in our project. The following paragraph has some variables, some HTML and components inside:
```
```
Although it looks complex, there's really nothing special here. Just wrap the content of the paragraph in [`Trans`](https://lingui.dev/ref/vue.md#trans) and let the compiler do the magic:
```
```
Let's see how this message actually looks in the message catalog. Run the [`extract`](https://lingui.dev/ref/cli.md#extract) command and take a look at the message:
```
#: src/Inbox.vue:20
msgid "See all <0>unread messages0> or <1>mark them1> as read."
msgstr ""
```
You may notice that components and html tags are replaced with indexed tags (`<0>`, `<1>`). This is a little extension to the ICU MessageFormat which allows rich-text formatting inside translations. Components and their props remain in the source code and don't scare our translators. Also, in case we change a `class`, we don't need to update our message catalogs.
Under the hood, the elements are moved to named slots of the `Trans` component, so all their attributes, bindings and event listeners keep working:
```
```
caution
Structural directives (`v-if`, `v-for`) can't be used on elements *inside* a message, as the message must be static for translators. Put them on the `Trans` element itself, or move the condition outside of the message.
### Template to MessageFormat Transformations[](#template-to-messageformat-transformations "Direct link to Template to MessageFormat Transformations")
At first glance, these transformations might seem somewhat unconventional; however, they are straightforward, intuitive, and align well with Vue principles. There is no need to focus on MessageFormat, as the library handles its creation for us. We can write our templates as we typically would and simply wrap the text in the [`Trans`](https://lingui.dev/ref/vue.md#trans) component.
Let's see some examples with MessageFormat equivalents:
```
Hello {{ name }}
```
Any expressions are allowed, not just simple variables. The only difference is, only the variable name will be included in the extracted message:
* Any expression -> positional argument:
```
Hello {{ user.name }}
```
* Object, arrays, function calls -> positional argument:
```
The random number is {{ Math.random() }}
```
* Use the `ph` macro to give a meaningful name to a placeholder:
```
Hello {{ ph({ name: user.name }) }}
```
* Elements might get tricky, but like we saw, it's really easy:
```
Read more.
```
```
Dear Watson,
it's not exactly what I had in my mind.
```
caution
Try to keep your messages simple and avoid complex expressions. During extraction, these expressions will be replaced by placeholders, resulting in a lack of context for translators.
Similarly, to prevent numbered tag placeholders like `<0>` from depriving translators of context, use [named tag placeholders](https://lingui.dev/ref/conf.md#macrojsxplaceholderattribute) and enforce them with [`no-unnamed-tag-placeholders`](https://github.com/lingui/eslint-plugin/blob/main/docs/rules/no-unnamed-tag-placeholders.md).
### Dates and Numbers[](#dates-and-numbers "Direct link to Dates and Numbers")
Take a look at the message in the footer of our component. It is a bit special because it contains a date:
```
```
Dates (as well as numbers) are formatted differently in different languages, but we don't have to do this manually. The heavy lifting is done by the [`Intl` object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl).
The `i18n` object can be accessed with the [`useLingui`](https://lingui.dev/ref/vue.md#uselingui) composable. It returns a reactive reference, so a `computed` that reads `i18n.value.locale` is re-evaluated when the language changes:
src/Inbox.vue
```
```
This will format the date using the conventional format for the active language. To format numbers, use `Intl.NumberFormat` in a similar way.
### Message ID[](#message-id "Direct link to Message ID")
At this point, we'll explain what the message ID is and how to set it manually. Translators work with *message catalogs*. No matter what format we use, it's just a mapping of a message ID to the translation.
Here's an example of a simple message catalog in **Czech** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Pondělí |
| Tuesday | Úterý |
| Wednesday | Středa |
... and the same catalog in **French** language:
| Message ID | Translation |
| ---------- | ----------- |
| Monday | Lundi |
| Tuesday | Mardi |
| Wednesday | Mercredi |
The message ID is *what all catalogs have in common* – "Lundi" and "Pondělí" represent the same message in different languages.
There are two approaches for creating a message ID:
* Automatically generated from message (e.g. `Monday`) and context, if available.
* Explicit message ID set by the developer (e.g. `days.monday`), using the `id` attribute: `Monday`.
info
Refer to the [Explicit vs Generated IDs](https://lingui.dev/guides/explicit-vs-generated-ids.md) guide for more information about the pros and cons of each approach.
## Plurals[](#plurals "Direct link to Plurals")
Let's take a closer look at the following code in our component:
```
{{
messagesCount === 1
? `There's ${messagesCount} message in your inbox.`
: `There are ${messagesCount} messages in your inbox.`
}}
```
This message is a bit special, because it depends on the value of the `messagesCount` variable. Most languages use different forms of words when describing quantities - this is called [pluralization](https://lingui.dev/guides/plurals.md).
What's tricky is that different languages use different number of plural forms. For example, English has only two forms - singular and plural - as we can see in the example above. However, Czech language has three plural forms. Some languages have up to 6 plural forms and some don't have plurals at all!
info
Lingui uses `Intl.PluralRules` which is supported in [every modern browser](https://caniuse.com/intl-pluralrules) and can be polyfilled for older. So you don't need to setup anything special.
### English Plural Rules[](#english-plural-rules "Direct link to English Plural Rules")
How do we know which plural form we should use? It's very simple: we, as developers, only need to know plural forms of the language we use in our source. Our component is written in English, so looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en) we'll need just two forms:
`one`
> Singular form
`other`
> Plural form
We don't need to select these forms manually. We'll use the `Plural` component, which takes a `value` prop and based on the active language, selects the right plural form:
```
```
This component will render `There's 1 message in your inbox` when `messagesCount = 1` and `There are # messages in your inbox` for any other values of `messagesCount`. `#` is a placeholder, which is replaced with `value`.
Let's run the [`extract`](https://lingui.dev/ref/cli.md#extract) command to see the extracted message:
```
{messagesCount, plural,
one {There's # message in your inbox}
other {There are # messages in your inbox}
}
```
In the catalog, you'll see the message in a single line. Here we have wrapped it to make it more readable.
### Beware of Zeroes\
Just a short detour, because it's a common misunderstanding. You may wonder why the following code doesn't work as expected:
```
```
This component will render `There are 0 messages in your inbox` for `messagesCount = 0`. Why so? Because English doesn't have `zero` plural form. Looking at [English plural rules](http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#en), it's:
| N | Form |
| - | --------------------- |
| 0 | other |
| 1 | one |
| n | other (anything else) |
However, decimal numbers (even `1.0`) always use the `other` form:
```
There are 0.0 messages in your inbox.
```
### Exact Forms[](#exact-forms "Direct link to Exact Forms")
Going back to our example, what if we specifically want to display `There are no messages` when `messagesCount = 0`? This is where exact forms come in handy:
```
```
tip
MessageFormat allows exact forms, like `=0`. However, attributes can't start with `=`, so we need to write `_N` instead of `=0`.
It works with any number, allowing for extensive customization as follows:
```
```
Exact matches always take precedence over plural forms.
### Variables and Components[](#variables-and-components "Direct link to Variables and Components")
Let's go back to our original pluralized message:
```
```
To include variables or elements within a plural form, write the form as a named slot instead of an attribute:
```
There's # message in your inbox, {{ name }}
There are # messages in your inbox, {{ name }}
```
Nested `Plural` and `Select` components, elements, variables, and expressions are all supported, providing the flexibility needed for any use case.
## Internationalization Outside of Templates[](#internationalization-outside-of-templates "Direct link to Internationalization Outside of Templates")
So far, we have learned how to translate strings within a template. However, what if we need to translate content that is outside the template or pass a translation as an attribute?
In our example, we have the following code:
```
const markAsRead = () => {
alert("Marked as read.");
};
```
To translate it, we will use the [`useLingui`](https://lingui.dev/ref/macro.md#uselingui) macro:
```
```
Now the `Marked as read.` message would be picked up by the extractor, and available for translation in the catalog.
You could also pass variables and use any other macro in the message:
```
const { t } = useLingui();
const markAsRead = () => {
const userName = "User1234";
alert(t`Hello ${userName}, your messages marked as read!`);
};
```
tip
The `t` function also works inside templates, for example to translate element attributes such as `alt` in an `img` tag or `placeholder` in an `input`. The template compiler takes care of the rest:
```
```
caution
All Core Macros cannot be used at the module level. They must be used within a component or function. See the [Macros](https://lingui.dev/ref/macro.md#using-macros) documentation for more information.
## Review[](#review "Direct link to Review")
After all modifications, the final i18n-ready component looks like this:
src/Inbox.vue
```
```
That's it for this tutorial! For more details, see the reference documentation or check out additional tutorials. Happy Internationalizing!
## See Also[](#see-also "Direct link to See Also")
* [`@lingui/vue` Reference](https://lingui.dev/ref/vue.md)
* [`@lingui/extractor-vue` Reference](https://lingui.dev/ref/extractor-vue.md)
* [Examples](https://lingui.dev/examples.md)
---