К основному содержанию
скилл CX Codex

migrate-i18next-to-lingui — скилл для Claude Code: миграция

Скилл migrate-i18next-to-lingui для Claude Code переносит проект с i18next и react-i18next на Lingui — от конфигурации до каталогов переводов. Помогает поэтапно заменить API.

MIT 197 установок ★ 12 обновлён 2026-11-04

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add lingui/skills --skill migrate-i18next-to-lingui -a claude-code
Открыть на GitHub

Что делает migrate-i18next-to-lingui

Скилл разбирает миграцию проекта с i18next и react-i18next на Lingui. Он охватывает установку пакетов, создание lingui.config.js, настройку Babel, SWC или Vite, замену инициализации, перенос React-компонентов и строк из JavaScript или TypeScript.

Отдельные шаги посвящены plural-формам, namespace, конвертации существующих каталогов и запуску lingui extract и lingui compile. В примерах показаны переходы от useTranslation, i18n.t() и Trans i18nKey к API Lingui. Для Lingui 6 нужен Node.js ≥ 22.19 или ≥ 24; на более старом Node.js пакеты @lingui/* нужно закрепить на ^5.

Какие задачи решает

  • перенести React-компоненты с useTranslation на useLingui
  • заменить вызовы i18n.t() и t() на макросы Lingui
  • перевести plural-ключи i18next в ICU MessageFormat
  • настроить lingui.config.js и сборку через Vite, Babel или SWC
  • конвертировать существующие JSON-каталоги переводов

Примеры запросов агенту

  • Перенеси этот проект с i18next и react-i18next на Lingui, сохранив ключи сообщений.
  • Замени useTranslation, Trans i18nKey и вызовы i18n.t() в исходниках на эквиваленты Lingui.
  • Настрой каталоги переводов, plural-формы и сборку для проекта на Vite.

Как установить migrate-i18next-to-lingui

1Через Skills CLI (Vercel)

npx skills add lingui/skills --skill migrate-i18next-to-lingui -a claude-code

2Вручную: положить файлы

~/.claude/skills/migrate-i18next-to-lingui/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/migrate-i18next-to-lingui/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о migrate-i18next-to-lingui

Как установить migrate-i18next-to-lingui в Claude Code?

Выполните npx skills add lingui/skills --skill migrate-i18next-to-lingui -a claude-code, затем проверьте файл ~/.claude/skills/migrate-i18next-to-lingui/SKILL.md.

Что делает migrate-i18next-to-lingui?

Скилл описывает перенос i18next и react-i18next на Lingui: настройку пакетов и сборки, замену API в React и JavaScript, работу с plural-формами, namespace и каталогами переводов.

Какая версия Node.js нужна для Lingui 6?

Lingui 6 работает в режиме ESM и требует Node.js ≥ 22.19 или ≥ 24. На более старом Node.js нужно использовать пакеты @lingui/* версии ^5.

Исходный текст

SKILL.md · MIT
---
name: migrate-i18next-to-lingui
description: Migrate 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.
---

# Migrate i18next to Lingui

## Migration Checklist

```
- [ ] Step 1: Install Lingui packages
- [ ] Step 2: Create lingui.config.js
- [ ] Step 3: Set up build tooling (Babel/SWC/Vite)
- [ ] Step 4: Replace i18n initialization
- [ ] Step 5: Migrate React components (useTranslation → useLingui, Trans → Trans)
- [ ] Step 6: Migrate JS/TS strings (t() → t``)
- [ ] Step 7: Migrate plurals
- [ ] Step 8: Migrate namespaces
- [ ] Step 9: Convert existing translation catalogs
- [ ] Step 10: Run lingui extract && lingui compile
- [ ] Step 11: Remove i18next packages
```

## Step 1: Install Lingui

> **Node version gate**: Lingui 6 is ESM-only and requires Node.js ≥ 22.19 (or ≥ 24). On older Node, pin all `@lingui/*` packages to `^5`.

```bash
# Core (always required)
npm install @lingui/core @lingui/react

# CLI (dev)
npm install --save-dev @lingui/cli

# Macro support - pick one based on build tool:
# Vite (transforms macros itself — see Step 3)
npm install --save-dev @lingui/vite-plugin
# Babel
npm install --save-dev @lingui/babel-plugin-lingui-macro
# SWC
npm install --save-dev @lingui/swc-plugin
```

## Step 2: Create `lingui.config.js`

```js
import { defineConfig } from "@lingui/cli";

export default defineConfig({
  sourceLocale: "en",
  locales: ["en", "de", "fr"], // match your existing locales
  catalogs: [
    {
      path: "<rootDir>/src/locales/{locale}/messages",
      include: ["src"],
    },
  ],
});
```

## Step 3: Configure Build Tooling

**Vite** (`vite.config.ts`):
```ts
import { lingui } from "@lingui/vite-plugin";
import react from "@vitejs/plugin-react"; // or @vitejs/plugin-react-swc

export default {
  plugins: [react(), lingui({ macroTransform: true })],
};
```

`macroTransform: true` (`@lingui/vite-plugin` 6.9.1+) transforms the macros with a prebuilt native binary — the React plugin needs no Lingui configuration, so `@vitejs/plugin-react` v5 and v6 both work. Without the option, `lingui()` only compiles catalogs. On a build platform without a prebuilt binary, use a Babel or SWC macro plugin — the lingui-framework-setup skill lists the platforms and has both fallbacks.

The `lingui()` plugin also compiles `.po` catalogs on the fly, so on Vite the app can import catalogs directly and skip the `lingui compile` step entirely:

```ts
// Dynamic import; the .po extension is mandatory
const { messages } = await import(`./locales/${locale}/messages.po`);
```

For TypeScript, declare the module so `.po` imports type-check:

```ts
// src/vite-env.d.ts
declare module "*.po" {
  import type { Messages } from "@lingui/core";
  export const messages: Messages;
}
```

**Babel** (`.babelrc` or `babel.config.js`):
```json
{ "plugins": ["macros"] }
```

**Next.js with SWC** (`next.config.js`):
```js
module.exports = {
  experimental: {
    swcPlugins: [["@lingui/swc-plugin", {}]],
  },
};
```

**Build-tooling caveats** (Babel/SWC paths; the Vite native transform has none of them): `@lingui/swc-plugin` must be version-matched to your SWC runtime, plugin entries must be `[name, options]` tuples (a bare string silently disables macros), and `@vitejs/plugin-react@6` removed Babel support entirely — see the `swc-plugin-compatibility` skill for all three.

## Step 4: Replace i18n Initialization

**Before (i18next):**
```js
import i18next from "i18next";
import { initReactI18next } from "react-i18next";

i18next.use(initReactI18next).init({
  lng: "en",
  resources: { en: { translation: { key: "Hello world" } } },
});
```

**After (Lingui):**
```js
import { i18n } from "@lingui/core";
import { I18nProvider } from "@lingui/react";
import { messages } from "./locales/en/messages";

i18n.load("en", messages);
i18n.activate("en");

function App() {
  return <I18nProvider i18n={i18n}>{/* app */}</I18nProvider>;
}
```

**Dynamic locale switching:**
```js
async function changeLocale(locale) {
  const { messages } = await import(`./locales/${locale}/messages`);
  i18n.load(locale, messages);
  i18n.activate(locale);
}
```

## Step 5: Migrate React Components

### `useTranslation` → `useLingui`

**Before:**
```jsx
import { useTranslation } from "react-i18next";

function MyComponent() {
  const { t } = useTranslation();
  return <p>{t("greeting")}</p>;
}
```

**After:**
```jsx
import { useLingui } from "@lingui/react/macro";

function MyComponent() {
  const { t } = useLingui();
  return <p>{t`Hello World`}</p>;
}
```

### `Trans` component

**Before:**
```jsx
import { Trans } from "react-i18next";

<Trans i18nKey="welcome">Hello World!</Trans>
```

**After:**
```jsx
import { Trans } from "@lingui/react/macro";

<Trans>Hello World!</Trans>
```

For explicit IDs (when preserving i18next keys):
```jsx
<Trans id="welcome">Hello World!</Trans>
```

### `Trans` with interpolation

**Before:**
```jsx
<Trans i18nKey="greeting" values={{ name }}>Hello {{ name }}!</Trans>
```

**After:**
```jsx
<Trans>Hello {name}!</Trans>
```

## Step 6: Migrate JS/TS Strings

### Simple strings

| i18next | Lingui |
|---------|--------|
| `t('key')` | `t\`Message text\`` |
| `t('key', { name })` | `t\`Hello ${name}\`` |
| `t('key', { defaultValue: 'Hi' })` | `t\`Hi\`` |

**Before:**
```js
import i18next from "i18next";

const msg = i18next.t("greeting", { name: "Tom" });
```

**After:**
```jsx
import { useLingui } from "@lingui/react/macro";

function MyComponent() {
  const { t } = useLingui();
  const msg = t`Hello ${name}`;
}
```

**In vanilla JS (outside components):**
```js
import { t } from "@lingui/core/macro";

const msg = t`Hello ${name}`;
```

### Preserving explicit keys from i18next

If you want to keep the i18next message IDs:
```js
import { t } from "@lingui/core/macro";

// i18next: t('navigation.home')
const msg = t({ id: "navigation.home", message: "Home" });
```

### Module-level / lazy strings

**Before (i18next):**
```js
const LABELS = {
  active: "Active",
  inactive: "Inactive",
};
// translated at render time
```

**After (Lingui):**
```js
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react";

const LABELS = {
  active: msg`Active`,
  inactive: msg`Inactive`,
};

function StatusDisplay({ status }) {
  const { _ } = useLingui();
  return <div>{_(LABELS[status])}</div>;
}
```

## Step 7: Migrate Plurals

i18next uses separate keys per plural form. Lingui uses ICU MessageFormat in a single message.

**Before (i18next):**
```json
{
  "item_one": "{{count}} item",
  "item_other": "{{count}} items"
}
```
```js
t("item", { count });
```

**After (Lingui) - JSX:**
```jsx
import { Plural } from "@lingui/react/macro";

<Plural value={count} one="# item" other="# items" />
```

**After (Lingui) - JS strings:**
```js
import { plural } from "@lingui/core/macro";

const msg = plural(count, {
  one: "# item",
  other: "# items",
});
```

**Exact matches** (i18next `_0`):
```jsx
<Plural
  value={count}
  _0="No items"
  one="# item"
  other="# items"
/>
```

## Step 8: Migrate Namespaces

i18next namespaces (`useTranslation('common')`) map to Lingui **catalog paths**. Two approaches:

**Option A - Single catalog (simplest):**
Remove namespaces and use one unified catalog. Update `lingui.config.js` to include all source directories.

**Option B - Multiple catalogs (preserves namespace separation):**
```js
// lingui.config.js
catalogs: [
  {
    path: "<rootDir>/src/locales/{locale}/common",
    include: ["src/components/common"],
  },
  {
    path: "<rootDir>/src/locales/{locale}/auth",
    include: ["src/components/auth"],
  },
]
```

With multiple catalogs, load them all at startup:
```js
import { messages as commonMessages } from "./locales/en/common";
import { messages as authMessages } from "./locales/en/auth";

i18n.load("en", { ...commonMessages, ...authMessages });
i18n.activate("en");
```

## Step 9: Convert Existing Translation Catalogs

See [catalog-conversion.md](references/catalog-conversion.md) for and patterns.

**Key concept:** i18next uses JSON with dotted keys; Lingui uses `.po` files with the message as the ID (or an explicit ID you provide).

## Step 10: Build & Verify

Run the full verification loop in this order — each stage catches what the previous one can't:

```bash
npx lingui extract --clean   # extracts all messages → .po files, drops obsolete entries
npx lingui compile           # compiles .po → runtime message catalogs
npx tsc --noEmit             # type errors from changed imports/APIs
npm run build                # macro transform actually runs in the real build
```

On Vite with `@lingui/vite-plugin` importing `.po` catalogs directly (Step 3), skip `lingui compile` — the plugin compiles at dev/build time and there are no compiled catalog files to manage.

Add to `package.json`:
```json
{
  "scripts": {
    "i18n:extract": "lingui extract",
    "i18n:compile": "lingui compile"
  }
}
```

For TypeScript:
```bash
npx lingui compile --typescript
```

### Recall Check: Find Strings the Migration Missed

A green build only proves the migrated strings work — not that all strings were migrated. Two checks:

**1. No i18next remnants.** All of these should return nothing:

```bash
grep -rn "from ['\"]i18next\|from ['\"]react-i18next" src/
grep -rn "useTranslation\|i18nKey\|i18next.t(" src/
```

**2. No unwrapped user-facing strings.** Run `eslint-plugin-lingui`'s `no-unlocalized-strings` rule over the tree — it catches hardcoded strings that were never in i18next to begin with, plus any `defaultValue` text left behind as plain strings:

```js
// eslint.config.js
import pluginLingui from "eslint-plugin-lingui";

export default [
  {
    plugins: { lingui: pluginLingui },
    rules: {
      "lingui/no-unlocalized-strings": ["warn", {
        ignore: ["^[A-Z0-9_-]+$"],                    // enums, constants
        ignoreNames: ["className", "src", "data-testid"],
        ignoreFunctions: ["console.*", "cn", "cva"],
      }],
    },
  },
];
```

The scan is deliberately over-inclusive — review each hit and either wrap it or confirm it's a non-UI string (class names, keys, URLs). Keep the plugin installed afterwards as a permanent guardrail. Report any strings you deliberately leave unwrapped rather than silently skipping them.

For the full audit loop — tuned scanner config, bounded fix rounds, residual reporting — use the **find-unwrapped-strings** skill. The check above is its migration-scoped subset.

## Step 11: Remove i18next

```bash
npm uninstall i18next react-i18next
```

## Common Patterns Reference

### Date/Number Formatting

**Before (i18next):**
```js
t("intlDateTime", { val: new Date() });
```

**After (Lingui):**
```jsx
import { useLingui } from "@lingui/react/macro";

function Component() {
  const { i18n } = useLingui();
  return <span>{new Intl.DateTimeFormat(i18n.locale).format(date)}</span>;
}
```

**Custom formats** (added with `i18next.services.formatter.add(name, fn)`, used as `{{val, name}}`): Lingui 6.12+ registers them with `i18n.setFormatters({ name: (value, { locale, param }) => … })`. The signature differs from i18next's `(value, lng, options)`. A translation keeps the format as `{val, name}`. A source message can't: the macros only generate `{val}`, so where the source text applied the format, apply it in code before the value reaches the message. The names `number`, `date`, `time`, `plural`, `select` and `selectordinal` are reserved, so rename an i18next format that uses one of them. The lingui-best-practices skill has the full recipe (integration recipes, custom formatters).

### Context (disambiguation)

**Before (i18next):**
```js
t("right", { context: "direction" });
```

**After (Lingui):**
```jsx
<Trans context="direction">right</Trans>
// or
t({ message: "right", context: "direction" });
```

### Gender / Select

**Before (i18next):**
```json
{ "pronoun_male": "He", "pronoun_female": "She", "pronoun_other": "They" }
```

**After (Lingui):**
```js
import { select } from "@lingui/core/macro";

const pronoun = select(gender, {
  male: "He",
  female: "She",
  other: "They",
});
```

## Pitfalls

- **Don't call `t\`...\`` at module level.** Use `msg\`...\`` instead and translate with `_(descriptor)` at render time.
- **After locale change**, call both `i18n.load(locale, messages)` and `i18n.activate(locale)`.
- **Wrap the entire app** in `<I18nProvider i18n={i18n}>` before any component uses `useLingui` or `Trans`.
- **Always run `lingui compile`** before building for production; the app imports compiled `.js` catalogs, not `.po` files.
- **Generated IDs change if message text changes.** If stability matters, use explicit `id` props.

## Additional Resources

- [Detailed migration patterns](references/migration-patterns.md)
- [Catalog conversion guide](references/catalog-conversion.md)
- [Lingui docs](https://lingui.dev)
- [Lingui vs i18next comparison](https://lingui.dev/misc/i18next)

© lingui · MIT · lingui/skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
i18next-localization i18next Скилл i18next-localization настраивает локализацию приложения через i18next: находит жёстко заданные строки, оборачивает их в вызовы переводов и собирает файлы локалей. Locize можно подключить отдельно. CX Codex +1 ★ 251звёзд репо internationalization-i18n aj-geddes Скилл internationalization-i18n для Claude Code помогает внедрять интернационализацию и локализацию в приложении. Он включается для работы с переводами, форматами и языками с письмом справа налево. CX Codex +1 648установок i18n-localization davila7 Скилл i18n-localization для Claude, который помогает вынести строки в файлы переводов, разобраться с локалями и поддержкой RTL. CX Codex +1 251установок add-localization Microsoft Скилл add-localization настраивает многоязычность в SPA-сайтах Power Pages на React, Vue или Angular. Помогает добавить языки, переключатель локалей и исправить конфигурацию i18n. CX Codex +1 ★ 1 167звёзд репо migrate-radix-to-base shadcn-ui Скилл migrate-radix-to-base для Claude Code переносит компоненты и проекты с Radix UI на Base UI. Запускается по просьбе заменить библиотеку или перенести отдельный компонент. CX Codex +1 37 800установок i18n-expert daymade Скилл i18n-expert настраивает и проверяет локализацию интерфейса: заменяет строки ключами, сверяет локали и форматирование. Нужен при работе с React, Next.js или Vue. CX Codex +1 2 800установок

Из того же набора6

lingui-best-practices Скилл lingui-best-practices помогает внедрять Lingui для локализации интерфейсов и каталогов переводов. Пригодится при добавлении i18n в приложения на React, Vue или JavaScript. CX Codex +1 811установок enhanced-message-context Скилл enhanced-message-context для Claude Code расставляет комментарии для переводчиков в сообщениях Lingui и решает, каким строкам они нужны — двусмысленным подписям и непрозрачным плейсхолдерам вроде {count}. CX Codex +1 630установок swc-plugin-compatibility Скилл swc-plugin-compatibility помогает устранить сбои сборки и несовместимость @lingui/swc-plugin с Next.js, Vite и Rspack, когда макросы локализации не преобразуются. CX Codex +1 305установок find-unwrapped-strings Скилл find-unwrapped-strings находит пользовательские строки в проекте Lingui, которые не обёрнуты макросами перевода. Запускайте его после настройки или миграции, чтобы проверить, что осталось вне каталогов. CX Codex +1 165установок lingui-framework-setup Скилл lingui-framework-setup настраивает интернационализацию с Lingui под Next.js, Remix, TanStack Start или Vite. Предотвращает ошибки сборки макросов и утечки локалей на сервере. CX Codex +1 159установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой