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

bundle-splitting — скилл для Claude Code: разбивка JS-бандла

Скилл учит агента делить большой JavaScript-бандл на части, чтобы быстрее рисовалась первая страница и приложение становилось интерактивным.

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

Что делает bundle-splitting

Скилл объясняет, как разбивать бандл на несколько меньших. Агент получает инструкции по работе с Webpack и Rollup: вынести код, который не нужен для первого рендера, в отдельный бандл и следить за временем до интерактивности (TTI).

Внутри — описание механики: браузер грузит, парсит и компилирует код ещё до первой отрисовки, поэтому лишний объём бьёт по FCP и LCP. Пример из материала: разделение на main.bundle.js и emoji-picker.bundle.js сокращает начальную загрузку. Скилл подхватывается для файлов **/*.js и **/*.ts.

Полезен, если у вас тяжёлый бандл и медленный первый экран. Но скилл не даёт готовых конфигов — решения по точкам разделения принимает агент вместе с вами. На слабых устройствах и медленных сетях выигрыш от меньшего бандла заметнее всего.

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

  • разделить большой JS-бандл на несколько частей
  • вынести код, нужный только для отдельных маршрутов, из начальной загрузки
  • сократить время до First Contentful Paint и Largest Contentful Paint
  • уменьшить объём кода, который грузится до первого рендера
  • разобраться, как разделение бандла влияет на Time To Interactive

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

  • посмотри мой бандл и предложи, как разбить его на части
  • вынеси код emoji-picker в отдельный бандл, чтобы ускорить первый рендер
  • помоги снизить LCP: что из моего кода можно грузить не сразу

Как установить bundle-splitting

1Через Skills CLI (Vercel)

npx skills add PatternsDev/skills --skill bundle-splitting -a claude-code

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

~/.claude/skills/bundle-splitting/SKILL.md

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

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

Вопросы о bundle-splitting

Как установить bundle-splitting в Claude?

Выполните npx skills add PatternsDev/skills --skill bundle-splitting -a claude-code. После этого файл скилла окажется в ~/.claude/skills/bundle-splitting/SKILL.md.

Что делает bundle-splitting?

Учит агента разбивать JavaScript-бандл на несколько меньших и отделять код, который не нужен для первого рендера. Цель — сократить FCP, LCP и время до интерактивности.

С какими бандлерами работает скилл?

В инструкциях названы Webpack и Rollup — именно их агент использует для разделения кода.

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

SKILL.md · MIT
---
name: bundle-splitting
description: Teaches bundle splitting techniques for web performance. Use when your application has a large JavaScript bundle that affects load times or when you need to reduce FCP/LCP.
paths:
  - "**/*.js"
  - "**/*.ts"
license: MIT
metadata:
  author: patterns.dev
  version: "1.1"
related_skills:
  - "module-pattern"
  - "singleton-pattern"
---

# Bundle Splitting

When building a modern web application, bundlers such as [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/guide/en/) take an application's source code, and bundle this together into one or more bundles. When a user visits a website, the bundle is requested and loaded in order to display the data to the user's screen.

JavaScript engines such as [V8](https://v8.dev/docs) are able to parse and compile data that's been requested by the user as it's being loaded. Although modern browsers have evolved to parse and compile the code as quickly and performantly as possible, the developer is still in charge of optimizing two steps in the process: the loading time and execution time of the requested data. We want to make sure we're keeping the execution time as short as possible to prevent blocking the main thread.

## When to Use

- Use this when your application has a large JavaScript bundle that affects load times
- This is helpful when you want to reduce First Contentful Paint (FCP) and Largest Contentful Paint (LCP)
- Use this when parts of your code are only needed for specific user interactions or routes

## Instructions

- Use bundlers like Webpack or Rollup to split code into multiple smaller bundles
- Separate code that isn't needed for the initial render into its own bundle
- Consider the impact on Time To Interactive (TTI) and prioritize critical rendering code

## Details

Even though modern browsers are able to stream the bundle as it arrives, it can still take a significant time before the first pixel is painted on the user's device. The bigger the bundle, the longer it can take before the engine reaches the line on which the first rendering call has been made. Until that time, the user has to stare at a blank screen.

We want to display data to the user as quickly as possible. A larger bundle leads to an increased amount of loading time, processing time, and execution time. It would be great if we could reduce the size of this bundle, in order to speed things up.

Instead of requesting one giant bundle that contains unnecessary code, we can split the bundle into multiple smaller bundles!

By bundle-splitting the application, we can reduce the time it takes to load, process and execute a bundle! By reducing the loading and execution time, we can reduce the time it takes before the first content has been painted on the user's screen, the First Contentful Paint (FCP), and the time it takes before the largest component has been rendered to the screen, the Largest Contentful Paint (LCP).

Although being able to see data on our screen is great, we don't just want to _see_ the content. In order to have a fully functioning application, we want users to be able to _interact_ with it as well! The UI only becomes interactive after the bundle has been loaded and executed. The time it takes before all content has been painted to the screen and has been made interactive, is called the Time To Interactive (TTI).

A bigger bundle doesn't necessarily mean a longer execution time. It could happen that we loaded a ton of code that the user won't even use! Maybe some parts of the bundle will only get executed on a certain user interaction, which the user may or may not do!

The engine still has to load, parse and compile code that's not even used on the initial render before the user is able to see anything on their screen. Although the parsing and compilation costs can be practically ignored due to the browser's performant way of handling these two steps, fetching a larger bundle than necessary can hurt the performance of your application. Users on low-end devices or slower networks will see a significant increase in loading time before the bundle has been fetched.

Instead of initially requesting parts of the code that don't have a high priority in the current navigation, we can separate this code from the code that's needed in order to render the initial page.

By bundle-splitting the large bundle into two smaller bundles, `main.bundle.js` and `emoji-picker.bundle.js`, we reduce the initial loading time by fetching a smaller amount of data.

## Source

- [patterns.dev/vanilla/bundle-splitting](https://patterns.dev/vanilla/bundle-splitting)

© patterns.dev · MIT · PatternsDev/skills

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

Всё по теме «Фронтенд и UI» →
nextjs-bundle-analyzer davila7 Слэш-команда для Claude, которая разбирает размер бандла Next.js и подсказывает, что урезать. 560установок performance-optimization Mindrally Набор правил для веб-производительности: серверный рендеринг, CSS, JavaScript, ассеты и кэш. Полезен, когда агент пишет фронтенд и вы хотите задать ему планку. CX Codex +1 848установок plugin-bundle-size grafana Помогает уменьшить размер входного файла module.js в плагинах приложений Grafana через React.lazy и разделение чанков в Webpack. CX Codex +1 4 200установок rollup-bundler Mindrally Скилл задаёт агенту правила конфигурации Rollup.js: форматы вывода, внешние зависимости, tree-shaking и плагины для сборки библиотек. CX Codex +1 657установок build-engineer VoltAgent Community Ускоряет сборку проекта и настраивает кэширование. Пригодится, если билд длится слишком долго или разросся монорепозиторий. 345установок rspeedy-bundle-size lynx-community Скилл разбирает, из чего складывается вес .lynx.bundle в rspeedy/ReactLynx, и подсказывает, за какой рычаг тянуть первым. CX Codex +1 458установок

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

import-on-interaction Скилл учит агента откладывать загрузку тяжёлых компонентов и виджетов до клика, наведения или ввода в форму. CX Codex +1 1 500установок loading-sequence Скилл объясняет агенту, в каком порядке грузить CSS, шрифты, JS и картинки, чтобы страница проходила Core Web Vitals. CX Codex +1 1 500установок preload Обучает агента настраивать предзагрузку критических ресурсов сайта. Помогает подтянуть шрифты, ключевые скрипты и баннеры, которые браузер находит слишком поздно. CX Codex +1 1 500установок compression Скилл объясняет, как сжимать JavaScript через Gzip и Brotli, чтобы скрипты быстрее уходили по сети. Полезен при настройке продакшен-сборки и медленных соединениях. CX Codex +1 1 500установок dynamic-import Обучает агента разделять бандл через dynamic import(). Скилл помогает отложить загрузку тяжёлых библиотек и диалогов до действий пользователя. CX Codex +1 1 500установок static-import Объясняет синтаксис import в ES2015 и помогает решить, когда модуль стоит грузить сразу, а когда переключиться на динамический импорт. CX Codex +1 1 400установок prpl Скилл обучает ИИ-агента паттерну PRPL для ускорения первой загрузки веб-приложений на слабых устройствах и медленных сетях. CX Codex +1 1 400установок tree-shaking Скилл объясняет tree shaking и подсказывает агенту, как убрать неиспользуемые экспорты из JavaScript-бандла. Пригодится, когда сборка тянет лишнее. CX Codex +1 1 400установок

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

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