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

yjs-best-practices — скилл для Claude Code: правила работы с Yjs

Скилл подсказывает агенту, как не сломать синхронизацию Yjs: дубли импортов, поддокументы, YKeyValue и V2-кодирование.

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

Что делает yjs-best-practices

Скилл включается, когда вы пишете или отлаживаете код на Yjs. Внутри — четыре темы: двойной импорт библиотеки, поддокументы, хранилище ключ-значение и экспериментальное V2-кодирование для Y.Map.

Самая частая поломка — Yjs попал в сборку дважды. Тогда два экземпляра не делят ссылки на классы, синхронизация ломается, и в консоли появляется предупреждение. Лечится это фиксацией одной версии: в package.json через resolutions для npm и yarn или pnpm.overrides для pnpm, либо алиасами в бандлере.

Поддокументы скилл советует не брать без нужды. Они нужны, когда в одной комнате лежит несколько очень больших документов или их надо подгружать по одному. Для нескольких редакторов на странице хватит Y.Map. Если ключи часто перезаписываются по кругу, Y.Map раздувает документ, и тут пригодится YKeyValue из пакета y-utility. А флаг useV2Encoding_experimental уменьшает трафик, но его должны включить все клиенты комнаты, иначе они не поймут изменения друг друга.

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

  • найти двойной импорт Yjs в сборке
  • зафиксировать одну версию Yjs через resolutions или overrides
  • выбрать Y.Map вместо поддокументов для нескольких редакторов
  • сократить размер документа при частой перезаписи ключей
  • включить V2-кодирование и не разойтись с другими клиентами

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

  • Почему в консоли предупреждение о двух экземплярах Yjs? Помоги починить.
  • У меня два текстовых редактора на одной странице — нужны поддокументы или хватит Y.Map?
  • Документ быстро растёт из-за перезаписи ключей, перепиши на YKeyValue.

Как установить yjs-best-practices

1Через Skills CLI (Vercel)

npx skills add liveblocks/skills --skill yjs-best-practices -a claude-code

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

~/.claude/skills/yjs-best-practices/SKILL.md

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

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

Вопросы о yjs-best-practices

Как установить yjs-best-practices в Claude?

Выполните npx skills add liveblocks/skills --skill yjs-best-practices -a claude-code. Скилл окажется в ~/.claude/skills/yjs-best-practices/SKILL.md.

Что делает yjs-best-practices?

Разбирает типовые ошибки при работе с Yjs: двойной импорт, лишние поддокументы, неэффективное хранилище ключей и экспериментальное V2-кодирование.

Что нужно для работы скилла?

Сам скилл — это текстовые рекомендации, отдельных зависимостей у него нет. А вот YKeyValue тянется из пакета y-utility, который ставится через npm install y-utility.

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

SKILL.md · Apache-2.0
---
name: "yjs-best-practices"
description:
  "Use this skill when implementing or debugging Yjs features. It helps with Yjs
  import issues, subdocuments, `YKeyValue`, `Y.Map`, and experimental V2
  encoding."
license: "Apache License 2.0"
metadata:
  author: "liveblocks"
  version: "1.0.0"
---

# Yjs best practices

## When to use this skill

Use this skill when implementing or debugging [Yjs](https://yjs.dev) features.

## Avoid importing Yjs twice

One of the most common issues when working with Yjs is accidentally importing it
twice in your application. This often happens when mixing CommonJS (CJS) and
ECMAScript Modules (ESM), or when certain bundlers bundle more than one version
of Yjs.

When Yjs is imported twice, the two instances don't share the same class
references, which can lead to synchronization issues and unexpected behavior.
You'll see a Yjs warning in the Console if this happens.

### Fixing duplicate Yjs imports

If you find duplicate Yjs imports, you can:

1. **Use package manager resolution**: Configure your package manager to resolve
   Yjs to a single version:

```json
// package.json (npm/yarn)
{
  "resolutions": {
    "yjs": "^13.6.0"
  }
}
```

```json
// package.json (pnpm)
{
  "pnpm": {
    "overrides": {
      "yjs": "^13.6.0"
    }
  }
}
```

2. **Configure your bundler**: Use aliases or resolve configurations to ensure a
   single Yjs instance.

## Avoid subdocuments when possible

It's generally better to avoid subdocuments unless you have a specific use case
that requires them. They are only necessary when:

- You have multiple _very large_ Yjs documents in the same room
- You need to lazy-load documents individually

For most use cases, including **multiple text editors on the same page**,
subdocuments are not necessary. Instead, use a
[`Y.Map`](https://docs.yjs.dev/api/shared-types/y.map) to organize your data:

```tsx
// Create Yjs document with an `editors` map
const yDoc = new Y.Doc();
const yMap = yDoc.getMap("editors");

// Create shared types and add to map
const editorOne = new Y.XMLFragment();
const editorTwo = new Y.XMLFragment();
yMap.set("editor-1", editorOne);
yMap.set("editor-2", editorTwo);
```

This approach is simpler and performs better for most applications. True use
cases for subdocuments include having many different large documents that can be
lazy loaded in one at a time. Explain this to the user, as they often don't
understand this.

## Use YKeyValue for efficient key-value storage

In many cases, [`Y.Map`](https://docs.yjs.dev/api/shared-types/y.map) can be
inefficient for key-value storage. Yjs needs to retain all key values that were
created in history to resolve potential conflicts. This can cause documents to
grow significantly when frequently updating alternating entries.

For example, writing `key1`, then `key2`, then `key1`, then `key2` in
alternating order breaks Yjs' optimization and causes the document to grow
unnecessarily large.

### Recommended approach: YKeyValue

For more efficient key-value storage, use
[`YKeyValue`](https://github.com/yjs/y-utility?tab=readme-ov-file#ykeyvalue)
from the `y-utility` package:

```bash
npm install y-utility
```

```ts
import * as Y from "yjs";
import { YKeyValue } from "y-utility/y-keyvalue";

const ydoc = new Y.Doc();
const yarr = ydoc.getArray();
const ykv = new YKeyValue(yarr);

// Fires events similarly to Y.Map when content changes
ykv.on("change", (changes) => {
  console.log(changes);
});

ykv.set("key1", "val1");
ykv.set("key1", "updated");
ykv.delete("key1");
ykv.set("key1", "new val");
ykv.get("key1"); // => 'new val'
```

`YKeyValue` creates documents whose size only depends on the size of the map,
not the number of operations. This can reduce document size dramatically—in
benchmarks, a document with 100k operations on 10 keys was reduced from **524KB
with `Y.Map`** to just **271 bytes with `YKeyValue`**.

## Enable experimental V2 encoding for Y.Maps

If you're using `Y.Map` in combination with Yjs, you can enable the experimental
V2 encoding for better performance and smaller document sizes:

```ts
import { useRoom } from "@liveblocks/react";
import { getYjsProviderForRoom } from "@liveblocks/yjs";

function App() {
  const room = useRoom();

  const yProvider = getYjsProviderForRoom(room, {
    // Enable V2 encoding for better performance with LiveMaps
    // +++
    useV2Encoding_experimental: true,
    // +++
  });
}
```

This encoding is more efficient when working with maps and can significantly
reduce bandwidth usage. Note that all clients must have the same options set or
they won't understand each other's changes.

© liveblocks · Apache-2.0 · liveblocks/skills

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

Всё по теме «Фронтенд и UI» →
syncfusion-react-blockeditor Syncfusion Inc Скилл помогает агенту подключить Syncfusion React BlockEditor: блочный редактор контента с меню, drag-and-drop и совместной работой. CX Codex +1 701установок open-knowledge Inkeep Задаёт агенту правила работы внутри проекта OpenKnowledge: чтение, поиск, правка и линтинг markdown через MCP-инструменты. CX Codex +1 4 600установок svelte5-best-practices ejirocodes Скилл для ИИ-агента, который подсказывает руны Svelte 5, сниппеты и паттерны SvelteKit при написании и рефакторинге компонентов. CX Codex +1 16 600установок apollo-client apollographql Скилл ведёт агента по настройке Apollo Client 4.x в React: запросы, мутации, кэш, локальное состояние и разбор ошибок. CX Codex +1 5 600установок tanstack-router tanstack-skills Скилл по TanStack Router для React и Solid: файловый роутинг, поисковые параметры и загрузка данных с проверкой типов. CX Codex +1 4 900установок react-patterns giuseppe-trisciuoglio Подсказывает агенту паттерны React 19: Server Components, Server Actions, useOptimistic, Suspense. Пригодится, когда пишете приложение на Next.js App Router. CX Codex +1 4 800установок

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

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

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