/lingui:lingui-best-practicesfrom Lingui Skills
Implements internationalization with Lingui in React, Vue, and JavaScript apps. Covers setup, message extraction, catalog compilation, and ICU MessageFormat patterns.
Ships in Lingui Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Lingui is a powerful internationalization (i18n) framework for JavaScript. This skill covers best practices for implementing i18n in React and vanilla JavaScript applications.
The standard Lingui workflow consists of these steps:
I18nProviderTrans, t, etc.)lingui extractlingui compileImport from these packages:
// React macros (recommended)
import { Trans, Plural, Select, useLingui } from "@lingui/react/macro";
// Core macros for vanilla JS
import { t, msg, plural, select } from "@lingui/core/macro";
// Runtime (rarely used directly)
import { I18nProvider } from "@lingui/react";
import { i18n } from "@lingui/core";
Vue 3: the examples here are React. In a Vue project import the macros from @lingui/vue/macro and the runtime from @lingui/vue. Templates use {{ name }} inside <Trans>, _0 for exact plural forms (attributes can't start with =), named slots (<template #one>) for plural forms with elements or variables, and useLingui() returns i18n as a ref (i18n.value.locale in <script>). Setup and template rules: the lingui-framework-setup skill, Vue reference. Catalog hygiene, message design and the shared locale module below apply as written.
Wrap your application with I18nProvider:
import { I18nProvider } from "@lingui/react";
import { i18n } from "@lingui/core";
import { messages } from "./locales/en/messages";
i18n.load("en", messages);
i18n.activate("en");
function App() {
return (
<I18nProvider i18n={i18n}>
{/* Your app */}
</I18nProvider>
);
}
The tree assumes a macro transform runs at build time (Babel, SWC or the Vite plugin). Code that runs with no build step — a Node.js script, a serverless function, a test runner — takes the runtime macro instead: see integration-recipes.md.
Work through these questions in order:
Plural (JSX) or plural (strings). Never wrap a count-dependent string in plain Trans — that bakes English plural rules into the message.TransuseLingui() + t`...`msg descriptor, resolved with t(descriptor) or _(descriptor) at render timet from @lingui/core/macroIf the string needs a translator comment, take the object form of whichever macro the tree picks — t`…` and msg`…` have nowhere to attach one. Deciding that while you wrap costs nothing; converting a whole codebase afterwards does not. See the enhanced-message-context skill.
Some destinations expect a plain string and will not take a macro at all — a Zod message, a count inside an aria-label, a server function's return value, an Intl formatter. Those have their own recipes: integration-recipes.md.
The Trans macro is the primary way to translate JSX:
import { Trans } from "@lingui/react/macro";
// Simple text
<Trans>Hello World</Trans>
// With variables
<Trans>Hello {userName}</Trans>
// With components (rich text)
<Trans>
Read the <a href="/docs">documentation</a> for more info.
</Trans>
// Extracted as: "Read the <0>documentation</0> for more info."
When to use: For any translatable text in JSX elements.
For strings outside JSX (attributes, alerts, function calls):
import { useLingui } from "@lingui/react/macro";
function MyComponent() {
const { t } = useLingui();
const handleClick = () => {
alert(t`Action completed!`);
};
return (
<div>
<img src="..." alt={t`Image description`} />
<button onClick={handleClick}>{t`Click me`}</button>
</div>
);
}
When to use: Element attributes, alerts, function parameters, any non-JSX string.
The macro hook returns i18n as well as t, and both are bound to the React context — so one hook covers reading the active locale, formatting against it, and subscribing the component to locale changes. One import covers it — the runtime useLingui from @lingui/react is for code that has no macro transform:
import { useLingui } from "@lingui/react/macro";
const { t, i18n } = useLingui();
i18n.locale; // "de-DE" — the active locale
new Intl.NumberFormat(i18n.locale) // format against it
When you need to define messages at module level or in arrays/objects:
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";
// Module-level constants
const STATUSES = {
active: msg`Active`,
inactive: msg`Inactive`,
pending: msg`Pending`,
};
function StatusList() {
const { _ } = useLingui();
return Object.entries(STATUSES).map(([key, message]) => (
<div key={key}>{_(message)}</div>
));
}
When to use: Module-level constants, arrays of messages, conditional message selection.
msg turns a string field into a MessageDescriptor, so TypeScript points at every consuming site — which is what makes this conversion safe to apply in bulk. Two things get through it:
React keys keep compiling. key={item.label} becomes an object key, which React stringifies to [object Object] — identical for every row, so reconciliation degrades and the only signal is a console warning. Key on an identifier, never on the copy:
// ❌ compiles; every key is now identical
{NAV.map((item) => <li key={item.label}>{t(item.label)}</li>)}
// ✅
{NAV.map((item) => <li key={item.to}>{t(item.label)}</li>)}
String methods become type errors with a tempting wrong fix. LABELS[k].toLowerCase() fails to compile — correctly — but t(LABELS[k]).toLowerCase() is not the repair. Lower-casing a translation breaks languages that capitalise by rule (German nouns) and is a no-op in scripts without case. If a lower-case variant is really needed, it is a second message with its own comment.
Use the Plural macro for quantity-dependent messages:
import { Plural } from "@lingui/react/macro";
<Plural
value={messageCount}
one="You have # message"
other="You have # messages"
/>
The # placeholder is replaced with the actual value.
Use _N syntax for exact number matches (takes precedence over plural forms):
<Plural
value={count}
_0="No messages"
one="One message"
other="# messages"
/>
Combine with Trans for complex messages:
<Plural
value={count}
one={`You have # message, ${userName}`}
other={
<Trans>
You have <strong>#</strong> messages, {userName}
</Trans>
}
/>
Use Intl directly:
import { useLingui } from '@lingui/react/macro';
function MyComponent() {
const { i18n } = useLingui();
const lastLogin = new Date();
const dateFormatter = useMemo(() => new Intl.DateTimeFormat(i18n.locale), [i18n.locale]);
return <Trans>Last login: {dateFormatter.format(lastLogin)}</Trans>;
}
When only some languages need a value shown differently (capitalized where German starts the sentence with it), code is the wrong place: it changes every language. Since Lingui 6.12, the translation can call a formatter registered on the instance, {type, capitalize}. See integration-recipes.md.
Provide a custom ID for stable message keys:
<Trans id="header.welcome">Welcome to our app</Trans>
When the same text has different meanings, use context:
<Trans context="direction">right</Trans>
<Trans context="correctness">right</Trans>
These create separate catalog entries.
Use context only when the same text genuinely needs different translations — not as a namespacing scheme (auth.login, settings.title). Identical strings with identical meaning should share one catalog entry so they are translated once.
Add context for translators:
<Trans comment="Greeting shown on homepage">Hello World</Trans>
Basic lingui.config.js:
import { defineConfig } from "@lingui/cli";
export default defineConfig({
sourceLocale: "en",
locales: ["en", "es", "fr", "de"],
catalogs: [
{
path: "<rootDir>/src/locales/{locale}/messages",
include: ["src"],
exclude: ["**/node_modules/**"],
},
],
});
For detailed configuration patterns, see configuration.md.
Lingui 6 (April 2026) is ESM-only and requires Node.js ≥ 22.19 (or ≥ 24). If the project can't meet that, pin all @lingui/* packages to ^5.
The deprecated string form format: "po" and the formatOptions option were removed in v6. Omit format entirely (PO remains the default), or pass a formatter instance to configure it:
import { defineConfig } from "@lingui/cli";
import { formatter } from "@lingui/format-po";
export default defineConfig({
// ...
format: formatter({ lineNumbers: false }),
});
lineNumbers: false keeps catalog diffs small — line-number comments change on almost every source edit.
Wire extraction and compilation into the project so they can't be forgotten:
{
"scripts": {
"lingui:extract": "lingui extract",
"lingui:compile": "lingui compile",
"dev": "lingui compile && vite",
"build": "lingui compile && vite build"
}
}
lingui compile && to the existing dev/build scripts — never replace them, and don't rely on a prebuild hook: pnpm ≥ 7 and Yarn Berry don't run pre/post hooks by default.src/locales/ also swallows the .po files — the translation source of truth:# ✅ compiled artifacts only
src/locales/**/messages.ts
src/locales/**/messages.js
# ❌ never — silently untracks the .po sources too
# src/locales/
Verify with git check-ignore: the compiled file must match, its .po sibling must not. Ignoring compiled catalogs is only safe because lingui compile runs before every build — don't do one without the other.
compileNamespace to how the app imports the catalog. If the code imports ./locales/en/messages as a .ts file, set compileNamespace: "ts" in lingui.config so a plain lingui compile regenerates exactly that artifact — no --typescript flag anyone can forget.@lingui/vite-plugin, the app can dynamically import .po catalogs directly (await import(\./locales/${locale}/messages.po`)`) — the plugin compiles on the fly, so there are no compiled catalog files to script around or gitignore.lingui compile && lingui extract --clean && git diff --exit-code -- src/locales):"i18n:check": "lingui check sync"
This fails the build when someone adds or edits a message without re-running extraction, and writes nothing. Mirror the flags the team extracts with (check sync --clean when the extract script uses --clean, same for --overwrite); otherwise the check compares against output the team never produces.
lingui check missing, which fails on translations still missing after fallbackLocales (the compile --strict rule, see configuration.md). Run it in the release pipeline rather than on every PR when translations arrive asynchronously from a TMS — otherwise every feature PR fails until translators catch up.Prefer macros over runtime components. Macros are compiled at build time, reducing bundle size:
// ✅ Good - uses macro
import { Trans } from "@lingui/react/macro";
// ❌ Avoid - runtime only
import { Trans } from "@lingui/react";
Avoid complex expressions in messages - they'll be replaced with placeholders:
// ❌ Bad - loses context
<Trans>Hello {user.name.toUpperCase()}</Trans>
// Extracted as: "Hello {0}"
// ✅ Good - clear variable name
const userName = user.name.toUpperCase();
<Trans>Hello {userName}</Trans>
// Extracted as: "Hello {userName}"
When extracting to a local variable isn't practical, name the placeholder inline with ph():
import { ph } from "@lingui/core/macro";
// Extracted as: "Hello {name}" instead of "Hello {0}"
t`Hello ${ph({ name: getUserName() })}`;
ph() also works inside Trans, Plural, and Select.
Named tags (<link>docs</link> instead of the numbered <0>docs</0>) are a lingui.config option: configuration.md has the setup and what it costs a project that already has translations.
Choose the right tool:
// ✅ For JSX content
<h1><Trans>Welcome</Trans></h1>
// ✅ For string values
const { t } = useLingui();
<img alt={t`Profile picture`} />
t at Module LevelA module-level t resolves once, at import time, against whatever locale is active then, and never updates. Define with msg and resolve at render time:
// ❌ Bad - frozen in the locale active at import
import { t } from "@lingui/core/macro";
const LABELS = [t`Red`, t`Green`, t`Blue`];
// ✅ Good - use msg for lazy translation
import { msg } from "@lingui/core/macro";
const LABELS = [msg`Red`, msg`Green`, msg`Blue`];
Not every string is a message. Leave these unwrapped:
className valuesconsole.* / logger output and developer-facing error codesdata-testid valuesLocale-prefixing URLs is a routing concern, not a translation concern — don't wrap paths in macros.
Install and configure eslint-plugin-lingui to catch common mistakes automatically:
npm install --save-dev eslint-plugin-lingui
// eslint.config.js
import pluginLingui from "eslint-plugin-lingui";
export default [
pluginLingui.configs["flat/recommended"],
];
Define locale facts once in a shared module with no React or framework imports, so it's safe to use from config, middleware, tests, and components alike:
// src/i18n/locales.ts
export const locales = ["en", "es", "fr", "ar"] as const;
export type Locale = (typeof locales)[number];
export const sourceLocale: Locale = "en";
const RTL_LOCALES = new Set(["ar", "he", "fa", "ur"]);
export const getDirection = (locale: string): "ltr" | "rtl" =>
RTL_LOCALES.has(locale.split("-")[0]) ? "rtl" : "ltr";
// "Deutsch", not "German" — each language name rendered in its own language
export const localeDisplayName = (locale: string) =>
new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
// `null` is in the signature on purpose: detect() and headers.get() both return it
export function resolveLocale(candidate: string | null | undefined): Locale {
if (!candidate) return sourceLocale;
if ((locales as readonly string[]).includes(candidate)) return candidate as Locale;
const base = candidate.split("-")[0]; // es-MX → es
return (locales as readonly string[]).includes(base) ? (base as Locale) : sourceLocale;
}
Signs this went wrong: getDirection or Intl.DisplayNames defined in more than one file, hardcoded dir="rtl" conditionals scattered around, hand-maintained language-name maps.
Layout caveat: don't keep both src/i18n.ts and src/i18n/ — the flat file shadows the directory's index.ts in module resolution, the build still passes, and the app is quietly wrong. Pick one layout.
import { i18n } from "@lingui/core";
async function changeLocale(locale) {
const { messages } = await import(`./locales/${locale}/messages`);
i18n.load(locale, messages);
i18n.activate(locale);
}
import { useEffect } from "react";
import { i18n } from "@lingui/core";
function loadCatalog(locale) {
return import(`./locales/${locale}/messages`);
}
function App() {
useEffect(() => {
loadCatalog("en").then(catalog => {
i18n.load("en", catalog.messages);
i18n.activate("en");
});
}, []);
return <I18nProvider i18n={i18n}>{/* ... */}</I18nProvider>;
}
A value that appears in many messages — the product name, a support address, the app version — goes in as a placeholder, so a rename changes one value and every message keeps its id and translation. Since Lingui 6.10, register it once on the instance and write the placeholder bare in the message:
// once, at startup — or setupI18n({ variables }) when you create the instance
i18n.setVariables({ appName: "Acme Notes" });
// in a component
const { t } = useLingui();
t`Questions about {appName}? Ask in the help center.`;
<Trans>Welcome to {"{appName}"}</Trans>; // the string literal keeps the braces as a placeholder
undefined and null fall through to the default.() => user.plan) is read on every render, but a change behind it triggers no re-render. i18n.setVariable(name, value) and setVariables emit change, so I18nProvider re-renders.{appName}: add a comment saying what it holds (enhanced-message-context).When using memoization, use the t function from the macro version:
import { useLingui } from "@lingui/react/macro";
import { msg } from "@lingui/core/macro";
import { useMemo } from "react";
const welcomeMessage = msg`Welcome!`;
function MyComponent() {
const { t } = useLingui(); // Macro version - reference changes with locale
// ✅ Safe - t reference updates with locale
const message = useMemo(() => t(welcomeMessage), [t]);
return <div>{message}</div>;
}
If you encounter issues:
include patterns in lingui.config.jslingui compileI18nProvider wraps your applingui compile --typescript for TypeScript projectsFor detailed common mistakes and pitfalls, see common-mistakes.md.
For the seams where Lingui meets a library that wants a plain string — validation schemas, plurals inside attributes, i18n._() with values, server-composed messages, Intl formatters — and for code with no build step, see integration-recipes.md. Each of those has a version that compiles, ships, and is wrong; the recipes lead with the trap.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
6 skills in this plugin
/enhanced-message-contextAdd translator comments to Lingui messages so translations are accurate. Use in Lingui projects when adding or modifying translatable messages, when strings are short or ambiguous ("Back", "Delete", "Post"), when placeholders are unclear ({count}, {name}), when deciding between comment and context, or when auditing extracted .po catalogs for missing translator context./find-unwrapped-stringsAudit a Lingui project for hardcoded user-facing strings that were never wrapped in macros. Use when asked to find untranslated, unwrapped, or hardcoded strings, to check i18n coverage, to audit what an i18n setup or migration missed, or when text renders in the source language after everything was supposedly translated./lingui-framework-setupSet up Lingui in a React or Vue framework. Use when adding Lingui to a Next.js App Router, Vite, React Router 7, Remix, TanStack Start, or Vue 3 (Vite, Nuxt) project, when wiring locale detection, locale-prefixed URLs, or SSR locale resolution, or when a working setup breaks after a framework or build-tool upgrade./migrate-i18next-to-linguiMigrate i18next/react-i18next projects to Lingui. Use when the user wants to replace i18next, react-i18next, useTranslation, i18n.t(), Trans i18nKey, or i18next JSON catalogs with Lingui equivalents. Covers package installation, config setup, code transformation patterns, plural migration, namespace handling, and catalog conversion./swc-plugin-compatibilityDiagnose and fix Lingui SWC plugin compatibility errors with Next.js, Vite, Rspack, or other SWC runtimes. Use when seeing errors like "failed to invoke plugin", "failed to run Wasm plugin transform", "Failed to deserialize program received from host", "Failed to execute SWC plugin", "out of bounds memory access", or "LayoutError" during builds with @lingui/swc-plugin — or when macros are silently not transformed (build succeeds but Trans/t render as raw untranslated output).npx claudepluginhub lingui/skills --plugin linguiOther plugins' skills for the same job