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

swc-plugin-compatibility — скилл для Claude Code: обзор и установка

Скилл swc-plugin-compatibility помогает устранить сбои сборки и несовместимость @lingui/swc-plugin с Next.js, Vite и Rspack, когда макросы локализации не преобразуются.

MIT 305 установок ★ 12 обновлён 2026-10-20

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

Что делает swc-plugin-compatibility

Скилл диагностирует ошибки Wasm-плагина Lingui при сборке: «failed to run Wasm plugin transform», сбои десериализации программы или ситуации, когда макросы Trans и t попадают в рендер сырым кодом. Проблема кроется не в коде приложения, а в несовпадении версий swc_core между хостом сборки и плагином.

Внутри разобран пошаговый порядок проверки. Сначала определяется хост: встроенный SWC в Next.js или конкретный резолв @swc/core в lockfile для Vite и Rspack. Далее по диапазону рантайма и таблице совместимости выбирается версия @lingui/swc-plugin, а также проверяются peerDependencies относительно @lingui/core. Для Vite описан альтернативный путь через нативный трансформ в @lingui/vite-plugin с параметром macroTransform: true, который исключает зависимость от ABI SWC.

Без точной фиксации версии плагина в devDependencies без символов ^ и ~ любое плановое обновление пакетов снова сломает сборку.

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

  • устранить ошибку failed to run Wasm plugin transform при сборке
  • исправить отображение необработанных макросов Trans и t
  • подобрать версию @lingui/swc-plugin под релиз Next.js или @swc/core
  • настроить нативный трансформ макросов в @lingui/vite-plugin

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

  • Помоги починить ошибку failed to invoke plugin в Next.js при сборке с Lingui
  • Какую версию @lingui/swc-plugin поставить для @swc/core из моего lockfile?
  • Как переключить сборку Vite на нативный трансформ макросов Lingui?

Как установить swc-plugin-compatibility

1Через Skills CLI (Vercel)

npx skills add lingui/skills --skill swc-plugin-compatibility -a claude-code

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

~/.claude/skills/swc-plugin-compatibility/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/swc-plugin-compatibility/

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

Вопросы о swc-plugin-compatibility

Как установить swc-plugin-compatibility в Claude Code?

Выполните команду npx skills add lingui/skills --skill swc-plugin-compatibility -a claude-code в терминале.

Что делает swc-plugin-compatibility?

Скилл даёт алгоритм решения ошибок совместимости @lingui/swc-plugin и рантаймов SWC в Next.js, Vite и Rspack.

Почему макросы Trans не переводятся, хотя сборка проходит без ошибок?

Это происходит при скрытом сбое трансформации из-за несовместимости версий swc_core; скилл помогает найти рабочий релиз плагина и зафиксировать его в проекте.

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

SKILL.md · MIT
---
name: swc-plugin-compatibility
description: Diagnose 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).
---

# SWC Plugin Compatibility

If you see errors like these during your build:

```
failed to invoke plugin on 'Some("/app/src/file.ts")'
failed to run Wasm plugin transform. Please ensure the version of `swc_core` used by the plugin is compatible with the host runtime.
    swc_plugin_runner: <n>
: Failed to deserialize program received from host
Failed to execute SWC plugin                      (Next.js / Turbopack wording of the same failure)
RuntimeError: out of bounds memory access         (older hosts)
LayoutError called Result::unwrap()               (older hosts)
```

**This is NOT a bug in your code or in Lingui.** The installed `@lingui/swc-plugin` was built against an `swc_core` version your SWC host cannot run.

## Why This Happens

Every `@lingui/swc-plugin` release is compiled against one pinned `swc_core` version — the plugin's [compatibility table](https://github.com/lingui/swc-plugin/blob/main/packages/lingui-macro/README.md#compatibility) lists them. The **host** (Next.js's bundled SWC, or the `@swc/core` that `@vitejs/plugin-react-swc` / Rspack resolves) accepts plugins from a range of `swc_core` versions. Outside that range the Wasm plugin cannot deserialize the AST it is handed, and the build fails on every file that uses a macro.

SWC has stabilised the plugin ABI over time, so mismatches are rarer than they were, but hosts still move past plugins and plugins past hosts (see lingui/swc-plugin [#250](https://github.com/lingui/swc-plugin/issues/250) and [#253](https://github.com/lingui/swc-plugin/issues/253) for one of each). The pairing is something to check, never assume.

## How to Fix

### Step 1: Identify the host and its resolved version

| Signal in the project | Host | Read the version from |
|---|---|---|
| `next` in dependencies, no `.babelrc` | Next.js's bundled SWC | `npm ls next` |
| `@vitejs/plugin-react-swc` | `@swc/core` | `npm ls @swc/core` — the **lockfile resolution**, not the caret range the plugin declares |
| Rspack / `@swc/core` directly | `@swc/core` | `npm ls @swc/core` |

Next.js embeds SWC and ignores any `@swc/core` in `package.json`; only the Next.js version decides its `swc_core`. On Vite, two projects with identical `package.json` can resolve different `@swc/core` versions — the lockfile is the source of truth.

**On Vite, the first fix is the native transform** ("Native Transform on Vite" below): `@lingui/vite-plugin` transforms the macros with its own prebuilt binary, outside the host's SWC, so there is no `swc_core` pairing and nothing to pin. The steps that follow are for Next.js, Rspack, and Vite builds the native binary can't run on.

### Step 2: Choose the plugin version

1. Read the host's accepted `swc_core` range. The error message usually prints a `https://plugins.swc.rs/versions/from-plugin-runner/<n>` URL — open it in a browser; for Next.js, select runtime `next` and the resolved version on https://plugins.swc.rs. The site is client-rendered, so a plain fetch returns an empty page; the fallback is the host's own pin: for Next.js, `swc_core` in the root `Cargo.toml` of the `vercel/next.js` tag (`v<version>`), for `@swc/core`, its GitHub release notes.
2. In the plugin's compatibility table, take the **newest** `@lingui/swc-plugin` whose `swc_core` falls inside that range.
3. Check its peer: `npm view @lingui/swc-plugin@<version> peerDependencies`. Each plugin major requires the matching `@lingui/core` major as a **required** peer (a newer plugin major may also admit the previous core major). A candidate whose peer excludes the installed `@lingui/core` is not a candidate — the install fails with `ERESOLVE` instead of the build failing. Pick the next-newest that passes, or go to "What If No Compatible Version Exists?".

The compatibility site has lagged behind releases before. When the table and the site disagree, or the host is newer than either lists, decide by building: try the newest plugin, then step back one `swc_core` row at a time until a macro-using file compiles.

Hosts drift independently, so two hosts in one repo (a Next.js app and a Vite app) can legitimately need two different plugin versions.

### Step 3: Pin exactly and confirm

```json
{
  "devDependencies": {
    "@lingui/swc-plugin": "<exact version>"
  }
}
```

Use an **exact version** (no `^` or `~`) so a routine dependency bump cannot move it. Done when the build passes on a file that uses a macro **and** the rendered output shows translated text rather than raw macro source.

## Keeping It Working

1. **Pin the plugin exactly** and exclude it from Renovate/Dependabot auto-merge; bump it deliberately, after checking the compatibility table.
2. **Treat host upgrades as plugin upgrades.** Hosts change `swc_core` in minor and patch releases, so a Next.js or `@vitejs/plugin-react-swc` bump needs the same check — put both packages in one update group.
3. **Build after any upgrade that touches SWC or the plugin.** The build, not the changelog, is the confirmation.

`@lingui/swc-plugin` does not track the other `@lingui/*` versions; it releases on its own cadence, so its version number carries no information about which `@lingui/core` it pairs with beyond the peer field.

## Example: Next.js Configuration

```js
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    swcPlugins: [
      ['@lingui/swc-plugin', {
        // Plugin options
      }],
    ],
  },
};

export default nextConfig;
```

## Example: .swcrc Configuration

```json
{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "experimental": {
      "plugins": [
        ["@lingui/swc-plugin", {}]
      ]
    }
  }
}
```

## Native Transform on Vite

```ts
// vite.config.ts — no @lingui/swc-plugin
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc"; // or @vitejs/plugin-react
import { lingui } from "@lingui/vite-plugin";

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

Requirements: `@lingui/vite-plugin` 6.9.1+, and a build machine with a prebuilt `@lingui/native-tools` binary (macOS, Windows, Linux glibc/musl on x64/arm64). There is no WASM fallback, so browser sandboxes such as StackBlitz WebContainers still need the SWC or Babel plugin.

## Example: Vite Configuration (SWC plugin)

```ts
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { lingui } from "@lingui/vite-plugin";

export default defineConfig({
  plugins: [
    react({ plugins: [["@lingui/swc-plugin", {}]] }),
    lingui(),
  ],
});
```

## Silent Failure: Wrong Plugin Entry Shape

Every SWC plugin entry must be a `[name, options]` **tuple**, even with empty options. Passing the plugin name as a bare string silently disables the macro transform: the build succeeds, but `<Trans>` never resolves and messages render as raw macro output.

```ts
// ❌ Silently does nothing
react({ plugins: ["@lingui/swc-plugin"] })

// ✅ Tuple with options object
react({ plugins: [["@lingui/swc-plugin", {}]] })
```

The same applies to Next.js `swcPlugins` and `.swcrc` `plugins` arrays.

Fixing the shape is the fix. On Vite, close by offering the native transform ("Native Transform on Vite") as a follow-up the user chooses: it drops the SWC plugin for good.

## What If No Compatible Version Exists?

When no plugin version that installs beside the project's `@lingui/core` fits the host, make an explicit choice rather than guessing:

1. **Move the host** to a version whose `swc_core` range has a matching plugin (usually forward: newer hosts accept newer plugins)
2. **Switch to the Babel transform** (`@lingui/babel-plugin-lingui-macro`) — see the caveats below
3. Open an issue or PR at https://github.com/lingui/swc-plugin

Forcing the install (`--legacy-peer-deps`) or downgrading `@lingui/core` to satisfy an old plugin's peer are not on this list: the first hides the mismatch until the build, the second regresses the runtime to please a build tool.

### Babel Fallback on Next.js

```bash
npm install -D @lingui/babel-plugin-lingui-macro babel-plugin-macros @babel/types
```

```json
// .babelrc
{ "presets": ["next/babel"], "plugins": ["macros"] }
```

Remove the `experimental.swcPlugins` entry. Three things the Babel path needs that the SWC plugin did not:

1. **`@babel/types` installed explicitly.** Next bundles its own Babel and does not expose it to plugins; without it the build fails with `Cannot find package '@babel/types'`.
2. **A `lingui.config.ts` (or `.js`/`.mjs`).** The Babel macro reads it at compile time; the SWC plugin never did, so a project that got by without one breaks here.
3. **Acceptance that `.babelrc` turns off Next's SWC compiler for the whole project** — Next prints `Disabled SWC as replacement for Babel because of custom Babel configuration`, and `compiler` options in `next.config` are ignored from then on. Builds get slower; prefer moving the host when that is an option.

### Babel Fallback Caveat: @vitejs/plugin-react 6

`@vitejs/plugin-react@6` dropped its internal Babel and **removed the `babel` option entirely**. On v6+, the classic form:

```ts
react({ babel: { plugins: ["@lingui/babel-plugin-lingui-macro"] } })
```

no longer works — a TypeScript config fails with TS2353 ("babel does not exist in type..."); a plain JS config is **silently ignored** and macros never get transformed.

Your options on Vite:

- Native transform: `lingui({ macroTransform: true })` with the stock React plugin — no Babel, no SWC plugin, no pin (preferred; see "Native Transform on Vite")
- Stay on SWC: `@vitejs/plugin-react-swc` + an exactly pinned `@lingui/swc-plugin` chosen by the steps above
- Run the macro as a standalone Babel pass (`@rolldown/plugin-babel` on Vite 8, `vite-plugin-babel` on Vite ≤ 7) — the lingui-framework-setup skill has the wiring
- Pin `@vitejs/plugin-react@^5`, which still supports the `babel` option

© lingui · MIT · lingui/skills

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

Все скиллы по теме «Фронтенд и UI» →
hot-reload-optimizer patricio0312rev Скилл hot-reload-optimizer для Claude Code оптимизирует hot module replacement и fast refresh в проектах на Vite, Next.js и webpack, ускоряя пересборки сервера разработки. CX Codex +1 267установок next-intl-add-language официальный github Скилл next-intl-add-language для GitHub Copilot добавляет язык в Next.js-приложение с next-intl: переводит en.json и обновляет маршрутизацию. Добавляет новую локаль в интерфейс. CX Codex +1 9 349установок i18n-expert daymade Скилл i18n-expert настраивает и проверяет локализацию интерфейса: заменяет строки ключами, сверяет локали и форматирование. Нужен при работе с React, Next.js или Vue. CX Codex +1 2 800установок internationalization-i18n Mindrally Скилл internationalization-i18n для Claude Code, Codex и Cursor задаёт правила интернационализации в веб- и мобильных проектах. Подключается при настройке перевода приложения на несколько языков. CX Codex +1 1 000установок next-intl-app-router liuchiawei Скилл next-intl-app-router для Claude Code. Настраивает next-intl с локалью в пути: конфиг, прокси, навигация и файлы сообщений. Закрывает добавление второго языка в проект. CX Codex +1 619установок localization-engineer daffy0208 Скилл localization-engineer по интернационализации приложений на Next.js с библиотекой next-intl. Помогает настроить переводы, плюрализацию, форматирование дат и RTL-стили. CX Codex +1 163установок

Из того же набора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установок migrate-i18next-to-lingui Скилл migrate-i18next-to-lingui для Claude Code переносит проект с i18next и react-i18next на Lingui — от конфигурации до каталогов переводов. Помогает поэтапно заменить API. CX Codex +1 197установок 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установок

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

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