mirror of
https://github.com/gromlab-ru/svg-sprites.git
synced 2026-07-22 04:40:17 +03:00
feat: добавить локализацию документации и скиллов
- добавлены английские README и руководства с переключением языка - сборка скиллов разделена на английскую и русскую версии - локализованные документы включены в npm-пакет
This commit is contained in:
331
README.md
331
README.md
@@ -1,77 +1,80 @@
|
||||
# @gromlab/svg-sprites
|
||||
|
||||
🇬🇧 English | [🇷🇺 Русский](README_RU.md)
|
||||
|
||||
 
|
||||
|
||||
CLI для генерации SVG-спрайтов и типизированных компонентов иконок для React и Next.js.
|
||||
A CLI for generating SVG sprites and typed icon components for React and Next.js.
|
||||
|
||||

|
||||
|
||||
## Навигация
|
||||
## Navigation
|
||||
|
||||
- [Возможности](#возможности)
|
||||
- [Таблица поддержки](#таблица-поддержки)
|
||||
- [Требования](#требования)
|
||||
- [Быстрый старт](#быстрый-старт)
|
||||
- [React + Vite](docs/ru/react-vite.md)
|
||||
- [React + Webpack 5](docs/ru/react-webpack.md)
|
||||
- [Next.js App Router](docs/ru/next-app.md)
|
||||
- [Next.js Pages Router](docs/ru/next-pages.md)
|
||||
- [Конфигурация](#конфигурация)
|
||||
- [Features](#features)
|
||||
- [Support matrix](#support-matrix)
|
||||
- [Requirements](#requirements)
|
||||
- [Quick start](#quick-start)
|
||||
- [React + Vite](docs/en/react-vite.md)
|
||||
- [React + Webpack 5](docs/en/react-webpack.md)
|
||||
- [Next.js App Router](docs/en/next-app.md)
|
||||
- [Next.js Pages Router](docs/en/next-pages.md)
|
||||
- [Configuration](#configuration)
|
||||
- [React](#react)
|
||||
- [Next.js](#nextjs)
|
||||
- [Множественные спрайты](#множественные-спрайты)
|
||||
- [Multiple sprites](#multiple-sprites)
|
||||
- [TypeScript](#typescript)
|
||||
- [Форматы спрайтов](#форматы-спрайтов)
|
||||
- [Способы отображения](#способы-отображения)
|
||||
- [Трансформации](#трансформации)
|
||||
- [Управление цветом иконок](#управление-цветом-иконок)
|
||||
- [Кеширование](#кеширование)
|
||||
- [Sprite formats](#sprite-formats)
|
||||
- [Rendering methods](#rendering-methods)
|
||||
- [Transformations](#transformations)
|
||||
- [Icon color management](#icon-color-management)
|
||||
- [Caching](#caching)
|
||||
- [SpriteViewer](#spriteviewer)
|
||||
- [Миграция с 0.1.x](docs/ru/migration-1.md)
|
||||
- [Документация](#документация)
|
||||
- [Migrating from 0.1.x](docs/en/migration-1.md)
|
||||
- [Documentation](#documentation)
|
||||
|
||||
## Возможности
|
||||
## Features
|
||||
|
||||
- **TypeScript-friendly** — типизированные React-компоненты, union-типы и runtime-списки доступных иконок.
|
||||
- **Чистая генерация** — generated-файлы автоматически исключаются из Git, спрайт не нужно вручную размещать в `public`, а генератор обновляет только принадлежащие ему файлы.
|
||||
- **Общие иконки без копирования** — SVG из локальной папки и `inputFiles` объединяются в один спрайт; один файл можно использовать в нескольких спрайтах.
|
||||
- **Встроенное интерактивное превью** — `<SpriteViewer>` подключается как страница приложения и показывает переданные React- и Next.js-спрайты с поиском, настройкой цветов и примерами использования.
|
||||
- **Настраиваемые трансформации SVG** — удаление `width` и `height` с сохранением `viewBox`, замена исходных цветов на CSS-переменные и transitions для `fill` и `stroke`.
|
||||
- **Отдельный кешируемый SVG asset** — SVG path-данные не попадают в JavaScript chunks, а сборщик выпускает файл с content hash.
|
||||
- **Множественные спрайты** — независимые React- и Next.js-модули со своими компонентами, типами и SVG assets.
|
||||
- **Server-first Next.js** — generated-компоненты работают в Server Components, SSR и SSG без директивы `'use client'`.
|
||||
- **Форматы под разные сценарии** — React и Next.js используют `stack`, legacy-режим также поддерживает `symbol` для существующих интеграций.
|
||||
- **AI-agent friendly** - the repository includes a ready-to-use skill with up-to-date documentation for configuring, migrating, and troubleshooting `@gromlab/svg-sprites`.
|
||||
- **TypeScript-friendly** - typed React components, union types, and runtime lists of available icons.
|
||||
- **Clean generation** - generated files are automatically excluded from Git, the sprite does not need to be placed in `public` manually, and the generator updates only files it owns.
|
||||
- **Shared icons without copying** - SVGs from the local folder and `inputFiles` are merged into a single sprite; one file can be used in multiple sprites.
|
||||
- **Built-in interactive preview** - `<SpriteViewer>` is integrated as an application page and displays the provided React and Next.js sprites with search, color controls, and usage examples.
|
||||
- **Configurable SVG transformations** - remove `width` and `height` while preserving `viewBox`, replace source colors with CSS variables, and add transitions for `fill` and `stroke`.
|
||||
- **Separate cacheable SVG asset** - SVG path data does not end up in JavaScript chunks, and the bundler emits a file with a content hash.
|
||||
- **Multiple sprites** - independent React and Next.js modules with their own components, types, and SVG assets.
|
||||
- **Server-first Next.js** - generated components work in Server Components, SSR, and SSG without the `'use client'` directive.
|
||||
- **Formats for different use cases** - React and Next.js use `stack`; legacy mode also supports `symbol` for existing integrations.
|
||||
|
||||
## Таблица поддержки
|
||||
## Support matrix
|
||||
|
||||
| Среда | Ключ мода API | Статус |
|
||||
| Environment | API mode key | Status |
|
||||
|---|---|---|
|
||||
| React + Vite | `react@vite` | Готово |
|
||||
| React + Webpack 5 | `react@webpack` | Готово |
|
||||
| Next.js 16.2+ App Router + Turbopack | `next@app/turbopack` | Готово |
|
||||
| Next.js 13.4+ App Router + Webpack 5 | `next@app/webpack` | Готово |
|
||||
| Next.js 16.2+ Pages Router + Turbopack | `next@pages/turbopack` | Готово |
|
||||
| Next.js 12.2+ Pages Router + Webpack 5 | `next@pages/webpack` | Готово |
|
||||
| Vue | — | Скоро |
|
||||
| Standalone | — | Скоро |
|
||||
| React + Vite | `react@vite` | Ready |
|
||||
| React + Webpack 5 | `react@webpack` | Ready |
|
||||
| Next.js 16.2+ App Router + Turbopack | `next@app/turbopack` | Ready |
|
||||
| Next.js 13.4+ App Router + Webpack 5 | `next@app/webpack` | Ready |
|
||||
| Next.js 16.2+ Pages Router + Turbopack | `next@pages/turbopack` | Ready |
|
||||
| Next.js 12.2+ Pages Router + Webpack 5 | `next@pages/webpack` | Ready |
|
||||
| Vue | - | Coming soon |
|
||||
| Standalone | - | Coming soon |
|
||||
|
||||
## Требования
|
||||
## Requirements
|
||||
|
||||
- Node.js 18 или новее;
|
||||
- пакет распространяется только как ESM и подключается через `import`;
|
||||
- React 18 или 19 требуется только для generated-компонентов и точки входа `@gromlab/svg-sprites/react`;
|
||||
- для типизации subpath exports используйте TypeScript 5+ с `moduleResolution: "bundler"`, `"node16"` или `"nodenext"`.
|
||||
- Node.js 18 or newer;
|
||||
- the package is distributed as ESM only and is loaded via `import`;
|
||||
- React 18 or 19 is required only for generated components and the `@gromlab/svg-sprites/react` entry point;
|
||||
- for subpath export typings, use TypeScript 5+ with `moduleResolution: "bundler"`, `"node16"`, or `"nodenext"`.
|
||||
|
||||
## Быстрый старт
|
||||
## Quick start
|
||||
|
||||
Для быстрого старта воспользуйтесь инструкцией для вашего стека:
|
||||
For a quick start, follow the guide for your stack:
|
||||
|
||||
- [React + Vite](docs/ru/react-vite.md)
|
||||
- [React + Webpack 5](docs/ru/react-webpack.md)
|
||||
- [Next.js App Router](docs/ru/next-app.md)
|
||||
- [Next.js Pages Router](docs/ru/next-pages.md)
|
||||
- [React + Vite](docs/en/react-vite.md)
|
||||
- [React + Webpack 5](docs/en/react-webpack.md)
|
||||
- [Next.js App Router](docs/en/next-app.md)
|
||||
- [Next.js Pages Router](docs/en/next-pages.md)
|
||||
|
||||
## Конфигурация
|
||||
## Configuration
|
||||
|
||||
### React
|
||||
|
||||
@@ -80,7 +83,7 @@ import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: [
|
||||
'../../shared/icons/check.svg',
|
||||
@@ -94,78 +97,78 @@ export default defineReactSpriteConfig({
|
||||
})
|
||||
```
|
||||
|
||||
| Опция | Тип | По умолчанию | Назначение |
|
||||
| Option | Type | Default | Purpose |
|
||||
|---|---|---|---|
|
||||
| `name` | `string` | Имя папки | Имя спрайта, компонента и публичных типов |
|
||||
| `description` | `string` | Нет | Описание для типов и debug-манифеста |
|
||||
| `inputFolder` | `string` | `./icons` | Папка с исходными SVG относительно конфига |
|
||||
| `inputFiles` | `string[]` | `[]` | Дополнительные SVG-файлы относительно конфига |
|
||||
| `transform` | `TransformOptions` | Все включены | [Настройки трансформации](#трансформации) исходных SVG |
|
||||
| `generatedNotice` | `boolean` | `true` | Полное либо короткое предупреждение в generated-файлах |
|
||||
| `name` | `string` | Folder name | Name of the sprite, component, and public types |
|
||||
| `description` | `string` | None | Description for types and the debug manifest |
|
||||
| `inputFolder` | `string` | `./icons` | Folder containing source SVGs, relative to the config |
|
||||
| `inputFiles` | `string[]` | `[]` | Additional SVG files, relative to the config |
|
||||
| `transform` | `TransformOptions` | All enabled | [Transformation settings](#transformations) for source SVGs |
|
||||
| `generatedNotice` | `boolean` | `true` | Full or short warning in generated files |
|
||||
|
||||
`inputFolder` и `inputFiles` объединяются в один спрайт, поэтому один SVG-файл можно использовать в нескольких спрайтах без копирования. Если неявной папки `./icons` нет, но `inputFiles` заполнен, генерация продолжается только по списку. Явно указанная отсутствующая папка считается ошибкой. Одинаковые пути дедуплицируются, а разные файлы с одинаковым именем иконки считаются ошибкой.
|
||||
`inputFolder` and `inputFiles` are merged into a single sprite, so one SVG file can be used in multiple sprites without copying. If the implicit `./icons` folder does not exist but `inputFiles` is populated, generation continues using only the list. An explicitly specified missing folder is an error. Duplicate paths are deduplicated, while different files with the same icon name are treated as an error.
|
||||
|
||||
`name` записывается в kebab-case и должно начинаться с латинской буквы. React и Next.js presets создают формат `stack`.
|
||||
`name` is stored in kebab-case and must start with a Latin letter. The React and Next.js presets produce the `stack` format.
|
||||
|
||||
### Next.js
|
||||
|
||||
Next.js использует тот же `svg-sprite.config.ts` и набор опций. Для типизации можно использовать отдельный хелпер:
|
||||
Next.js uses the same `svg-sprite.config.ts` and set of options. For type checking, you can use a dedicated helper:
|
||||
|
||||
```ts
|
||||
import { defineNextSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineNextSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
})
|
||||
```
|
||||
|
||||
Роутер и сборщик выбираются через mode key, поэтому переключение между Turbopack и Webpack всегда явно отражено в команде генерации.
|
||||
The router and bundler are selected through the mode key, so switching between Turbopack and Webpack is always explicitly reflected in the generation command.
|
||||
|
||||
## Множественные спрайты
|
||||
## Multiple sprites
|
||||
|
||||
Приложение может содержать несколько независимых спрайтов с разной областью использования:
|
||||
An application can contain several independent sprites for different scopes:
|
||||
|
||||
**Проблема:** один глобальный спрайт загружает иконки, которые текущему экрану не нужны.
|
||||
**Problem:** one global sprite loads icons that the current screen does not need.
|
||||
|
||||
**Решение:** общие иконки хранить глобально, а наборы страниц и крупных компонентов — в отдельных спрайтах, загружаемых вместе с ними.
|
||||
**Solution:** keep shared icons globally, and place icon sets for pages and large components in separate sprites that load alongside them.
|
||||
|
||||
```text
|
||||
global → GlobalIcon → общие иконки приложения
|
||||
analytics-page → AnalyticsPageIcon → иконки отдельной страницы
|
||||
file-manager → FileManagerIcon → иконки крупного компонента
|
||||
global -> GlobalIcon -> shared application icons
|
||||
analytics-page -> AnalyticsPageIcon -> icons for a specific page
|
||||
file-manager -> FileManagerIcon -> icons for a large component
|
||||
```
|
||||
|
||||
- **Глобальный спрайт** содержит небольшие общие иконки, используемые в разных частях приложения: навигацию, состояния и базовые действия.
|
||||
- **Спрайт страницы** загружается вместе с конкретным разделом и не увеличивает общий спрайт иконками, которые больше нигде не нужны.
|
||||
- **Спрайт крупного компонента** инкапсулирует собственный набор иконок сложного UI-модуля, например файлового менеджера или редактора.
|
||||
- **Global sprite** contains a small set of shared icons used in different parts of the application: navigation, states, and basic actions.
|
||||
- **Page sprite** loads with a specific section and does not increase the shared sprite with icons that are not needed anywhere else.
|
||||
- **Large component sprite** encapsulates the icon set of a complex UI module, such as a file manager or editor.
|
||||
|
||||
Каждая группа получает:
|
||||
Each group gets:
|
||||
|
||||
- собственный SVG asset;
|
||||
- собственный типизированный компонент;
|
||||
- отдельный список имён иконок;
|
||||
- отдельный debug-манифест;
|
||||
- независимый cache lifecycle.
|
||||
- its own SVG asset;
|
||||
- its own typed component;
|
||||
- a separate list of icon names;
|
||||
- a separate debug manifest;
|
||||
- an independent cache lifecycle.
|
||||
|
||||
|
||||
## TypeScript
|
||||
|
||||
Главная возможность TypeScript API — автодополнение имён иконок непосредственно в prop `icon`:
|
||||
The main feature of the TypeScript API is icon name autocomplete directly in the `icon` prop:
|
||||
|
||||
```tsx
|
||||
<FileManagerIcon icon="folder" />
|
||||
// ↑ редактор предлагает все иконки спрайта
|
||||
// ^ the editor suggests every icon in the sprite
|
||||
```
|
||||
|
||||
Имена SVG-файлов становятся допустимыми значениями `icon`. Опечатка или неизвестное имя сразу становятся ошибкой TypeScript:
|
||||
SVG file names become valid `icon` values. A typo or unknown name immediately becomes a TypeScript error:
|
||||
|
||||
```tsx
|
||||
<FileManagerIcon icon="unknown" /> // ошибка TypeScript
|
||||
<FileManagerIcon icon="unknown" /> // TypeScript error
|
||||
```
|
||||
|
||||
Для программного доступа generated-модуль экспортирует readonly-массив всех доступных иконок конкретного спрайта:
|
||||
For programmatic access, the generated module exports a readonly array of all icons available in a specific sprite:
|
||||
|
||||
```ts
|
||||
import { fileManagerIconNames } from './svg-sprite'
|
||||
@@ -173,39 +176,39 @@ import { fileManagerIconNames } from './svg-sprite'
|
||||
// readonly ['check', 'folder', ...]
|
||||
```
|
||||
|
||||
Этот список можно использовать в собственных каталогах, select-компонентах, тестах и других runtime-сценариях. Из него также выводится union-тип `FileManagerIconName`.
|
||||
You can use this list in custom catalogs, select components, tests, and other runtime scenarios. The `FileManagerIconName` union type is also derived from it.
|
||||
|
||||
Имена файлов с пробелами и другими небезопасными для SVG ID символами остаются частью публичного TypeScript API. Для внутреннего `<symbol id>` генератор создаёт стабильный hash ID.
|
||||
File names containing spaces and other characters unsafe for SVG IDs remain part of the public TypeScript API. For the internal `<symbol id>`, the generator creates a stable hash ID.
|
||||
|
||||
```text
|
||||
folder open.svg → icon="folder open" → id="icon-<stable-hash>"
|
||||
folder open.svg -> icon="folder open" -> id="icon-<stable-hash>"
|
||||
```
|
||||
|
||||
Для таких имён используйте generated-компонент или `id` из debug-манифеста. Ручные примеры ниже с `#<имя>` подходят только для имён, которые уже являются безопасными SVG ID.
|
||||
For such names, use the generated component or the `id` from the debug manifest. The manual examples below using `#<name>` are suitable only for names that are already safe SVG IDs.
|
||||
|
||||
## Форматы спрайтов
|
||||
## Sprite formats
|
||||
|
||||
`stack` — более современный формат, поэтому он используется по умолчанию. Иконки можно отображать через `<svg><use>`, `<img>` и CSS `background-image`.
|
||||
`stack` is the more modern format, so it is used by default. Icons can be rendered through `<svg><use>`, `<img>`, and CSS `background-image`.
|
||||
|
||||
`symbol` сохраняется для совместимости с существующими интеграциями и поддерживает отображение только через `<svg><use>`.
|
||||
`symbol` is retained for compatibility with existing integrations and supports rendering only through `<svg><use>`.
|
||||
|
||||
## Способы отображения
|
||||
## Rendering methods
|
||||
|
||||
### React-компонент — рекомендуется
|
||||
### React component - recommended
|
||||
|
||||
Generated-компонент предоставляет типизацию, автодополнение имён иконок и сам формирует URL SVG asset.
|
||||
The generated component provides type safety and icon name autocomplete, and constructs the SVG asset URL itself.
|
||||
|
||||
```tsx
|
||||
<FileManagerIcon icon="check" width={24} height={24} />
|
||||
```
|
||||
|
||||
Через `color` и `--icon-color-N` доступны одноцветные и многоцветные иконки.
|
||||
Monochrome and multicolor icons are supported through `color` and `--icon-color-N`.
|
||||
|
||||
### Самостоятельно через `<svg><use>`
|
||||
### Manually with `<svg><use>`
|
||||
|
||||
Хороший низкоуровневый способ с полным управлением размерами и цветами. React-компонент под капотом использует именно его.
|
||||
A good low-level method that provides full control over dimensions and colors. This is exactly what the React component uses under the hood.
|
||||
|
||||
Способ получения `spriteUrl` зависит от сборщика.
|
||||
How you obtain `spriteUrl` depends on the bundler.
|
||||
|
||||
**Vite:**
|
||||
|
||||
@@ -222,7 +225,7 @@ const spriteUrl = new URL(
|
||||
).href
|
||||
```
|
||||
|
||||
**Next.js с Webpack 5 или Turbopack:**
|
||||
**Next.js with Webpack 5 or Turbopack:**
|
||||
|
||||
```tsx
|
||||
const spriteUrl = new URL(
|
||||
@@ -231,7 +234,7 @@ const spriteUrl = new URL(
|
||||
).href
|
||||
```
|
||||
|
||||
После получения URL иконка отображается одинаково:
|
||||
After obtaining the URL, the icon is rendered the same way:
|
||||
|
||||
```tsx
|
||||
<svg width={24} height={24}>
|
||||
@@ -239,17 +242,17 @@ const spriteUrl = new URL(
|
||||
</svg>
|
||||
```
|
||||
|
||||
Vite, Webpack 5 и Next.js сами заменяют исходный путь на итоговый URL asset с hash.
|
||||
Vite, Webpack 5, and Next.js replace the source path with the final hashed asset URL automatically.
|
||||
|
||||
### Через `<img>` — менее эффективно
|
||||
### With `<img>` - less efficient
|
||||
|
||||
```tsx
|
||||
<img src={`${spriteUrl}#check`} width={24} height={24} alt="Готово" />
|
||||
<img src={`${spriteUrl}#check`} width={24} height={24} alt="Done" />
|
||||
```
|
||||
|
||||
SVG загружается как изолированное изображение: изменить его цвета через `color` или `--icon-color-N` нельзя.
|
||||
The SVG loads as an isolated image: its colors cannot be changed through `color` or `--icon-color-N`.
|
||||
|
||||
### Через CSS `background-image` — менее эффективно
|
||||
### With CSS `background-image` - less efficient
|
||||
|
||||
```css
|
||||
.icon {
|
||||
@@ -257,9 +260,9 @@ SVG загружается как изолированное изображен
|
||||
}
|
||||
```
|
||||
|
||||
Как и `<img>`, этот способ не позволяет управлять внутренними цветами SVG. Путь указывается относительно CSS-файла, а Vite/Webpack заменяет его на итоговый URL с hash при сборке.
|
||||
Like `<img>`, this method does not allow you to control internal SVG colors. The path is specified relative to the CSS file, and Vite/Webpack replaces it with the final hashed URL during the build.
|
||||
|
||||
### Через CSS mask — менее эффективно
|
||||
### With CSS mask - less efficient
|
||||
|
||||
```css
|
||||
.icon {
|
||||
@@ -268,37 +271,37 @@ SVG загружается как изолированное изображен
|
||||
}
|
||||
```
|
||||
|
||||
Mask оставляет только силуэт и окрашивает его одним цветом. Исходные цвета, gradients и различия между `fill` и `stroke` теряются.
|
||||
A mask retains only the silhouette and colors it with a single color. The original colors, gradients, and distinctions between `fill` and `stroke` are lost.
|
||||
|
||||
## Трансформации
|
||||
## Transformations
|
||||
|
||||
Все трансформации включены по умолчанию и настраиваются независимо через `transform`.
|
||||
All transformations are enabled by default and configured independently through `transform`.
|
||||
|
||||
| Опция | По умолчанию | Что делает |
|
||||
| Option | Default | What it does |
|
||||
|---|---|---|
|
||||
| `removeSize` | `true` | Удаляет `width` и `height` с корневого `<svg>`, сохраняя существующий `viewBox`. Размер иконки после этого задаётся снаружи. |
|
||||
| `replaceColors` | `true` | Заменяет цвета `fill` и `stroke` на `--icon-color-N`. Для одноцветной иконки fallback становится `currentColor`, для многоцветной сохраняются исходные цвета. |
|
||||
| `addTransition` | `true` | Добавляет `style="transition:fill 0.3s,stroke 0.3s;"` непосредственно цветным элементам SVG. Существующий `transition` не перезаписывается. |
|
||||
| `removeSize` | `true` | Removes `width` and `height` from the root `<svg>` while preserving the existing `viewBox`. The icon size is then set externally. |
|
||||
| `replaceColors` | `true` | Replaces `fill` and `stroke` colors with `--icon-color-N`. For a monochrome icon, the fallback becomes `currentColor`; for a multicolor icon, the original colors are preserved. |
|
||||
| `addTransition` | `true` | Adds `style="transition:fill 0.3s,stroke 0.3s;"` directly to colored SVG elements. An existing `transition` is not overwritten. |
|
||||
|
||||
Чтобы отключить преобразование, передайте для соответствующей опции `false`. Подробнее о результате `replaceColors` — в разделе [«Управление цветом иконок»](#управление-цветом-иконок).
|
||||
To disable a transformation, pass `false` for the corresponding option. For more details about the result of `replaceColors`, see [Icon color management](#icon-color-management).
|
||||
|
||||
## Управление цветом иконок
|
||||
## Icon color management
|
||||
|
||||
При включённой замене цветов генератор анализирует `fill` и `stroke` и преобразует их в CSS custom properties.
|
||||
When color replacement is enabled, the generator analyzes `fill` and `stroke` and converts them to CSS custom properties.
|
||||
|
||||
### Монохромные иконки
|
||||
### Monochrome icons
|
||||
|
||||
Если найден один цвет, fallback заменяется на `currentColor`:
|
||||
If one color is found, the fallback is replaced with `currentColor`:
|
||||
|
||||
```svg
|
||||
stroke="var(--icon-color-1, currentColor)"
|
||||
```
|
||||
|
||||
Цветом управляет CSS-свойство `color` внешнего `<svg>` или его родителя.
|
||||
The color is controlled by the CSS `color` property of the outer `<svg>` or its parent.
|
||||
|
||||
### Многоцветные иконки
|
||||
### Multicolor icons
|
||||
|
||||
Каждый уникальный цвет получает отдельную переменную с исходным fallback:
|
||||
Each unique color gets a separate variable with the original fallback:
|
||||
|
||||
```svg
|
||||
fill="var(--icon-color-1, #798198)"
|
||||
@@ -306,7 +309,7 @@ fill="var(--icon-color-2, #ffffff)"
|
||||
fill="var(--icon-color-3, #129d9d)"
|
||||
```
|
||||
|
||||
Страница может заменить только необходимые цвета:
|
||||
The page can override only the required colors:
|
||||
|
||||
```css
|
||||
.icon {
|
||||
@@ -315,62 +318,62 @@ fill="var(--icon-color-3, #129d9d)"
|
||||
}
|
||||
```
|
||||
|
||||
### Ограничения цветов
|
||||
### Color limitations
|
||||
|
||||
- `none`, `transparent`, `inherit`, `unset` и `initial` не заменяются;
|
||||
- цвета в атрибутах `fill`, `stroke` и inline `style` обрабатываются надёжнее всего;
|
||||
- CSS-классы и внешние stylesheets внутри исходного SVG не являются основным сценарием трансформации;
|
||||
- gradients, patterns, filters и значения `url(#...)` требуют отдельной проверки и могут быть несовместимы с автоматической заменой цветов;
|
||||
- CSS-переменные страницы доступны при `<svg><use>`, но недоступны внутри `<img>` и `background-image`.
|
||||
- `none`, `transparent`, `inherit`, `unset`, and `initial` are not replaced;
|
||||
- colors in `fill`, `stroke`, and inline `style` attributes are handled most reliably;
|
||||
- CSS classes and external stylesheets inside the source SVG are not the primary transformation use case;
|
||||
- gradients, patterns, filters, and `url(#...)` values require separate verification and may be incompatible with automatic color replacement;
|
||||
- page CSS variables are available with `<svg><use>`, but are not available inside `<img>` and `background-image`.
|
||||
|
||||
## Кеширование
|
||||
## Caching
|
||||
|
||||
Vite, Webpack и Next.js target выпускают спрайт отдельным asset с content hash:
|
||||
The Vite, Webpack, and Next.js targets emit the sprite as a separate asset with a content hash:
|
||||
|
||||
```text
|
||||
/assets/sprite-<hash>.svg
|
||||
```
|
||||
|
||||
Это даёт следующие свойства:
|
||||
This provides the following properties:
|
||||
|
||||
- SVG кешируется независимо от JavaScript;
|
||||
- изменение React-кода не меняет содержимое спрайта;
|
||||
- изменение иконок создаёт новый hash asset;
|
||||
- один файл используется всеми экземплярами generated-компонента;
|
||||
- SVG path-данные отсутствуют в JavaScript chunks.
|
||||
- the SVG is cached independently of JavaScript;
|
||||
- changes to React code do not alter the sprite contents;
|
||||
- icon changes produce a new hashed asset;
|
||||
- one file is used by every instance of the generated component;
|
||||
- SVG path data is absent from JavaScript chunks.
|
||||
|
||||
Vite target запрещает inline через `?no-inline`. Webpack 5 target использует Asset Modules через `new URL(..., import.meta.url)`.
|
||||
The Vite target prevents inlining through `?no-inline`. The Webpack 5 target uses Asset Modules through `new URL(..., import.meta.url)`.
|
||||
|
||||
## SpriteViewer
|
||||
|
||||
`SpriteViewer` — React-компонент для просмотра generated-спрайтов внутри debug-маршрута приложения.
|
||||
`SpriteViewer` is a React component for viewing generated sprites inside an application's debug route.
|
||||
|
||||
Он использует отдельные манифесты и показывает:
|
||||
It uses separate manifests and displays:
|
||||
|
||||
- группы спрайтов;
|
||||
- список и количество иконок;
|
||||
- поиск и системную светлую/тёмную тему;
|
||||
- модальное превью с `viewBox` и настройкой цветовых переменных;
|
||||
- примеры React, SVG, IMG и CSS с копированием кода.
|
||||
- sprite groups;
|
||||
- the icon list and count;
|
||||
- search and the system light/dark theme;
|
||||
- a preview modal with the `viewBox` and color variable controls;
|
||||
- React, SVG, IMG, and CSS examples with code copying.
|
||||
|
||||
Production-компоненты не импортируют debug-манифесты. Способ подключения Viewer зависит от сборщика:
|
||||
Production components do not import debug manifests. How you integrate the Viewer depends on the bundler:
|
||||
|
||||
- [React + Vite: автоматический `import.meta.glob`](docs/ru/react-vite.md#6-добавьте-debug-страницу);
|
||||
- [React + Webpack 5: статические `import()`](docs/ru/react-webpack.md#6-добавьте-debug-страницу);
|
||||
- [Next.js App Router](docs/ru/next-app.md#5-добавьте-spriteviewer);
|
||||
- [Next.js Pages Router](docs/ru/next-pages.md#5-добавьте-spriteviewer).
|
||||
- [React + Vite: automatic `import.meta.glob`](docs/en/react-vite.md#6-add-a-debug-page);
|
||||
- [React + Webpack 5: static `import()`](docs/en/react-webpack.md#6-add-a-debug-page);
|
||||
- [Next.js App Router](docs/en/next-app.md#5-add-spriteviewer);
|
||||
- [Next.js Pages Router](docs/en/next-pages.md#5-add-spriteviewer).
|
||||
|
||||
Viewer подключается из отдельной клиентской точки входа `@gromlab/svg-sprites/react` и не попадает в production-компоненты иконок.
|
||||
The Viewer is imported from the separate `@gromlab/svg-sprites/react` client entry point and is not included in production icon components.
|
||||
|
||||
### Тема Viewer
|
||||
### Viewer theme
|
||||
|
||||
По умолчанию `colorTheme="auto"`: Viewer следует `prefers-color-scheme` и реагирует на смену системной темы. Тему приложения можно передать явно:
|
||||
By default, `colorTheme="auto"`: the Viewer follows `prefers-color-scheme` and responds to system theme changes. The application theme can be passed explicitly:
|
||||
|
||||
```tsx
|
||||
<SpriteViewer sources={sources} colorTheme="dark" />
|
||||
```
|
||||
|
||||
Допустимые значения `colorTheme`: `auto`, `light`, `dark`. При управлении темой извне встроенный переключатель скрывается. Чтобы оставить его и обновлять тему приложения через Viewer, передайте callback:
|
||||
Valid `colorTheme` values are `auto`, `light`, and `dark`. When the theme is controlled externally, the built-in switch is hidden. To keep it and update the application theme through the Viewer, pass a callback:
|
||||
|
||||
```tsx
|
||||
<SpriteViewer
|
||||
@@ -380,16 +383,16 @@ Viewer подключается из отдельной клиентской т
|
||||
/>
|
||||
```
|
||||
|
||||
## Документация
|
||||
## Documentation
|
||||
|
||||
- [React + Vite](docs/ru/react-vite.md)
|
||||
- [React + Webpack 5](docs/ru/react-webpack.md)
|
||||
- [Next.js App Router](docs/ru/next-app.md)
|
||||
- [Next.js Pages Router](docs/ru/next-pages.md)
|
||||
- [Legacy mode](docs/ru/legacy.md)
|
||||
- [Миграция с 0.1.x](docs/ru/migration-1.md)
|
||||
- [Программный API](docs/ru/programmatic-api.md)
|
||||
- [React + Vite](docs/en/react-vite.md)
|
||||
- [React + Webpack 5](docs/en/react-webpack.md)
|
||||
- [Next.js App Router](docs/en/next-app.md)
|
||||
- [Next.js Pages Router](docs/en/next-pages.md)
|
||||
- [Legacy mode](docs/en/legacy.md)
|
||||
- [Migrating from 0.1.x](docs/en/migration-1.md)
|
||||
- [Programmatic API](docs/en/programmatic-api.md)
|
||||
|
||||
## Лицензия
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
Reference in New Issue
Block a user