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

rspress-custom-theme — скилл для Claude Code: тема Rspress v2

Скилл подсказывает агенту, как менять тему Rspress v2: от CSS-переменных до замены встроенных компонентов.

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

Что делает rspress-custom-theme

Скилл ведёт агента по четырём уровням кастомизации Rspress v2 — от самого лёгкого к тяжёлому. Сначала он выясняет цель: поменять цвета, поправить вёрстку, вставить свой блок или заменить компонент целиком. Дальше выбирает подходящий уровень. Логика простая: чем легче подход, тем проще пережить обновление Rspress.

Уровни такие. CSS-переменные — для брендовых цветов, фонов, шрифтов и теней. Переопределение BEM-классов вида .rp-nav или .rp-codeblock — когда переменных не хватает. Слоты Layout — чтобы добавить баннер, футер или логотип вокруг готовых компонентов. И eject — когда нужно полностью заменить встроенный компонент. Иконки меняются отдельно: именованный экспорт в theme/index.tsx перекрывает встроенный.

Для уровней 1A, 3 и 4 нужен файл theme/index.tsx рядом с docs/. Внутри theme/ импортируйте из @rspress/core/theme-original, а не из @rspress/core/theme — второй путь указывает на ваш же файл и даёт циклический импорт. Это главная ловушка при настройке. Скилл рассчитан на Rspress v2: если импорты в проекте идут из rspress/*, версия другая и часть приёмов не сработает.

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

  • поменять брендовые цвета и шрифты в теме Rspress
  • поправить стиль отдельного компонента, когда CSS-переменных не хватает
  • вставить свой баннер или футер вокруг готовых блоков
  • заменить встроенную иконку GitHub или поиска
  • выкинуть встроенный компонент и написать свой

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

  • Хочу поменять брендовые цвета в теме Rspress на фиолетовый
  • Добавь свой футер внизу каждой страницы Rspress
  • Замени иконку GitHub в шапке на свою SVG

Как установить rspress-custom-theme

1Через Skills CLI (Vercel)

npx skills add rstackjs/agent-skills --skill rspress-custom-theme -a claude-code

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

~/.claude/skills/rspress-custom-theme/SKILL.md

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

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

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

rsbuild-best-practices Задаёт правила настройки, проверки и отладки сборщика Rsbuild. Помогает настроить конфиг, оптимизировать бандл и выявить узкие места при компиляции. CX Codex +1 2 700установок rstest-best-practices Правила настройки и написания тестов Rstest: окружения, моки, снапшоты, покрытие и CI. Пригодится, когда проект переезжает на Rstest или тесты уже есть, но разъехались по стилю. CX Codex +1 1 400установок rslib-best-practices Скилл обучает агента правилам сборки библиотек на Rslib. Пригодится при настройке rslib.config.ts, разделении зависимостей и выводе деклараций. CX Codex +1 1 000установок rspress-best-practices Скилл задаёт агенту правила для сайтов на Rspress v2: конфигурация, навигация, MDX, ассеты, поиск и деплой. Пригодится, когда документация уже есть, а агент пишет по ней код. CX Codex +1 538установок rspack-v2-upgrade Ведёт проект с Rspack 1.x через переход на вторую версию: зависимости, конфиг, проверка сборки. Пригодится, когда мажорный апгрейд страшно начинать вручную. CX Codex +1 515установок rspress-description-generator Скилл дописывает поле description во frontmatter страниц Rspress, если его там нет. Пригодится, когда документация уже большая, а метаописания заполнены вручную через одну. CX Codex +1 498установок rsbuild-v2-upgrade Проводит проект с Rsbuild 1.x через миграцию на v2: зависимости, конфиг, сломанные опции. Пригодится, когда мажорное обновление иначе растянется на вечер. CX Codex +1 476установок migrate-to-rstest Переносит тесты из Jest, Vitest или Playwright Test в Rstest, сохраняя обнаружение, ассерты, моки, снапшоты и покрытие. Пригодится, когда надо переехать без переписывания сценариев. CX Codex +1 420установок

Похожие

preline-theme-generator htmlstreamofficial Генерирует CSS-темы для Preline UI из цветов бренда или настроения. Работает через локальные скрипты — не требует сети после установки. CX Codex +1 1 300установок tailwind-theme-builder jezweb Скилл настраивает тему Tailwind v4 с shadcn/ui и тёмным режимом: ставит зависимости, связывает CSS-переменные через @theme inline, подключает переключатель темы. CX Codex +1 3 200установок liquid-theme-standards benjaminsehl Скилл задаёт правила вёрстки и клиентских скриптов для тем Shopify. Помогает писать предсказуемый код в файлах .liquid и ресурсах ассетов. CX Codex +1 2 900установок color-mode-and-theme dembrandt Помогает выбрать цветовую схему проекта, решить вопрос о поддержке тёмной темы и выстроить токены без сломанного контраста. CX Codex +1 926установок mantine-custom-components mantinedev Скилл учит ИИ-агента создавать компоненты для Mantine 9.x по официальным паттернам библиотеки. Пригодится при настройке Styles API, CSS-переменных и фабрик компонентов. CX Codex +1 3 600установок contentful-custom-app-from-scratch contentful Помогает собрать кастомное приложение Contentful App Framework: от идеи и выбора локаций до локального теста и передачи. CX Codex +1 2 800установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о rspress-custom-theme

Как установить rspress-custom-theme в Claude?

Выполните npx skills add rstackjs/agent-skills --skill rspress-custom-theme -a claude-code. Скилл встанет в ~/.claude/skills/rspress-custom-theme/SKILL.md.

Что делает rspress-custom-theme?

Проводит агента по четырём уровням кастомизации темы Rspress v2: CSS-переменные, переопределение BEM-классов, слоты Layout и eject компонентов. Плюс замена встроенных иконок через именованный экспорт.

Для какой версии Rspress подходит скилл?

Для Rspress v2. Признак — импорты из @rspress/core/*. Если в проекте пути вида rspress/*, версия другая, и часть приёмов из скилла не сработает.

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

SKILL.md · MIT
---
name: rspress-custom-theme
description: Customize Rspress v2 themes with CSS variables, class overrides, Layout slots, icons, or component ejection.
---

# Rspress custom theme

Guide for customizing Rspress (v2) themes. Rspress offers four levels of customization, from lightest to heaviest. Always prefer the lightest approach that meets the requirement — lighter approaches are more maintainable and survive Rspress upgrades.

## Workflow

1. **Understand the user's goal** — what do they want to change? (colors, layout, inject content, replace a component entirely?)
2. **Pick the right level** using the decision flow below
3. **Set up `theme/index.tsx`** if needed (Levels 1A, 3, 4 all need it)
4. **Implement** following the patterns in this skill and reference files
5. **Verify** the user's Rspress version is v2 (imports use `@rspress/core/*` not `rspress/*`)

## Decision flow

| User wants to...                                                 | Level | Approach                    |
| ---------------------------------------------------------------- | ----- | --------------------------- |
| Change brand colors, fonts, spacing, shadows                     | 1     | CSS variables               |
| Adjust a specific component's style (borders, padding, etc.)     | 2     | BEM class overrides         |
| Add content around existing components (banners, footers, logos) | 3     | Layout slots (wrap)         |
| Override MDX rendering (custom `<h1>`, `<code>`, etc.)           | 3     | `components` slot           |
| Wrap the app in a provider (state, analytics, auth)              | 4     | Eject `Root`                |
| Replace built-in icons (logo, GitHub, search, etc.)              | —     | Icon re-export              |
| Completely replace a built-in component                          | 4     | Eject that component        |
| Add a global floating component (back-to-top, chat widget)       | —     | `globalUIComponents` config |
| Control page layout structure (hide sidebar, blank page)         | —     | Frontmatter `pageType`      |

---

## theme/index.tsx — The entry point

Levels 1A, 3, and 4 all require a `theme/index.tsx` file in the project root (sibling to `docs/`). This is the single entry point for all theme customizations:

```text
project/
├── docs/
├── theme/
│   ├── index.tsx        # Theme entry — re-exports + overrides
│   ├── index.css         # CSS variable / BEM overrides (optional)
│   └── components/       # Ejected components (Level 4)
└── rspress.config.ts
```

Minimal setup:

```tsx
// theme/index.tsx
import './index.css'; // optional
export * from '@rspress/core/theme-original';
```

**Critical import rule**: Inside `theme/` files, always import from `@rspress/core/theme-original`. The path `@rspress/core/theme` resolves to your own `theme/index.tsx`, which causes circular imports. (In `docs/` MDX files, `@rspress/core/theme` is fine — it correctly points to your custom theme.)

---

## Level 1: CSS variables

Override CSS custom properties for brand colors, backgrounds, text, code blocks, and more.

**Option A** — `theme/index.css` (use when you also have component overrides in `theme/index.tsx`):

```css
/* theme/index.css */
:root {
  --rp-c-brand: #7c3aed;
  --rp-c-brand-light: #8b5cf6;
  --rp-c-brand-dark: #6d28d9;
}
.dark {
  --rp-c-brand: #a78bfa;
}
```

**Option B** — `globalStyles` (use when you only need CSS changes, no component overrides):

```ts
// rspress.config.ts
export default defineConfig({
  globalStyles: path.join(__dirname, 'styles/custom.css'),
});
```

> **Full variable list**: Read `references/css-variables.md` for all available CSS variables with light/dark defaults.

---

## Level 2: BEM class overrides

All built-in components follow BEM naming: `.rp-[component]__[element]--[modifier]`.

Common targets: `.rp-nav`, `.rp-link`, `.rp-tabs`, `.rp-codeblock`, `.rp-codeblock__title`, `.rp-nav-menu__item--active`.

Use these in your CSS file for targeted style changes when CSS variables aren't granular enough.

---

## Level 3: wrap (Layout Slots)

Inject content at specific positions in the layout without replacing built-in components. Override `Layout` in `theme/index.tsx`:

```tsx
// theme/index.tsx
import { Layout as OriginalLayout } from '@rspress/core/theme-original';
export * from '@rspress/core/theme-original';

export function Layout() {
  return (
    <OriginalLayout beforeNavTitle={<MyLogo />} bottom={<CustomFooter />} />
  );
}
```

Use runtime hooks inside slot components — import from `@rspress/core/runtime`: `useDark()`, `useLang()`, `useVersion()`, `usePage()`, `useSite()`, `useFrontmatter()`, `useI18n()`.

> **All slots & examples**: Read `references/layout-slots.md` for the complete slot list and usage patterns including i18n and MDX component overrides.

---

## Level 4: eject

Copy a built-in component's source for full replacement. Only use when wrap/slots cannot achieve the customization.

```bash
rspress eject           # list available components
rspress eject DocFooter # eject to theme/components/DocFooter/
```

Then re-export in `theme/index.tsx` (named export takes precedence over the wildcard):

```tsx
export * from '@rspress/core/theme-original';
export { DocFooter } from './components/DocFooter';
```

> **Component list & patterns**: Read `references/eject-components.md` for available components, workflow, and common patterns.

---

## Custom icons

Rspress has 27 built-in icons used across the UI. You can replace any of them by re-exporting your own icon component with the same name — no ejection needed. This uses the same `theme/index.tsx` mechanism: your named export takes precedence over the wildcard re-export.

**Icon type**: Each icon is a React component or a URL string:

```ts
import type { FC, SVGProps } from 'react';
type Icon = FC<SVGProps<SVGSVGElement>> | string;
```

**Example 1** — Replace an icon with a custom SVG component:

```tsx
// theme/index.tsx
export * from '@rspress/core/theme-original';

// Named export overrides the wildcard — replaces the GitHub icon site-wide
export const IconGithub = (props: React.SVGProps<SVGSVGElement>) => (
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" {...props}>
    <path d="M12 2C6.477 2 2 6.484 2 12.017c0 ..." fill="currentColor" />
  </svg>
);
```

**Example 2** — Use an SVGR import:

```tsx
// theme/index.tsx
export * from '@rspress/core/theme-original';

import CustomGithubIcon from './icons/github.svg?react';
export const IconGithub = CustomGithubIcon;
```

**Using `SvgWrapper` in MDX or custom components**:

```mdx
import { SvgWrapper, IconGithub } from '@rspress/core/theme';

<SvgWrapper icon={IconGithub} width={24} height={24} />
```

**Available icons**: `IconArrowDown`, `IconArrowRight`, `IconClose`, `IconCopy`, `IconDeprecated`, `IconDown`, `IconEdit`, `IconEmpty`, `IconExperimental`, `IconExternalLink`, `IconFile`, `IconGithub`, `IconGitlab`, `IconHeader`, `IconJump`, `IconLink`, `IconLoading`, `IconMenu`, `IconMoon`, `IconScrollToTop`, `IconSearch`, `IconSmallMenu`, `IconSuccess`, `IconSun`, `IconTitle`, `IconWrap`, `IconWrapped`.

> **Source**: See the [icons source](https://github.com/web-infra-dev/rspress/blob/main/packages/core/src/theme/icons.ts) for default implementations.

---

## Global UI components

For components that should render on every page without theme overrides:

```ts
// rspress.config.ts
export default defineConfig({
  globalUIComponents: [
    path.join(__dirname, 'components', 'BackToTop.tsx'),
    [
      path.join(__dirname, 'components', 'Analytics.tsx'),
      { trackingId: '...' },
    ],
  ],
});
```

---

## Page types

Control layout per page via frontmatter `pageType`:

| Value      | Description                           |
| ---------- | ------------------------------------- |
| `home`     | Home page with navbar                 |
| `doc`      | Standard doc with sidebar and outline |
| `doc-wide` | Doc without sidebar/outline           |
| `custom`   | Custom content with navbar only       |
| `blank`    | Custom content without navbar         |
| `404`      | 404 error page                        |

Fine-grained: set `navbar: false`, `sidebar: false`, `outline: false`, `footer: false` individually.

---

## Common pitfalls

- **Circular import**: Using `@rspress/core/theme` instead of `@rspress/core/theme-original` in `theme/` files — causes infinite loop.
- **Eject over-use**: Ejecting when a Layout slot or CSS variable would suffice — creates upgrade burden.
- **Missing re-export**: Forgetting `export * from '@rspress/core/theme-original'` in `theme/index.tsx` — breaks all un-overridden components.
- **v1 imports**: Using `rspress/theme` or `@rspress/theme-default` — these are v1 paths. v2 uses `@rspress/core/theme-original`.

## Reference

- Custom theme guide: <https://rspress.rs/guide/basic/custom-theme>
- CSS variables: <https://rspress.rs/ui/vars>
- Layout component: <https://rspress.rs/ui/layout-components/layout>
- Built-in icons: <https://rspress.rs/ui/icons/>
- Built-in hooks: <https://rspress.rs/ui/hooks/>
- CLI commands (eject): <https://rspress.rs/api/commands>

© rstackjs · MIT · rstackjs/agent-skills

Смотрите также

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

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