mirror of
https://github.com/gromlab-ru/svg-sprites.git
synced 2026-07-22 12:40:21 +03:00
Compare commits
1 Commits
v1.1.2
...
docs/local
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b5b446d8f |
@@ -57,10 +57,10 @@ A CLI for generating SVG sprites and typed icon components for React and Next.js
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
| Next.js + App Router + Turbopack | `next@app/turbopack` | Ready |
|
||||
| Next.js + App Router + Webpack 5 | `next@app/webpack` | Ready |
|
||||
| Next.js + Pages Router + Turbopack | `next@pages/turbopack` | Ready |
|
||||
| Next.js + Pages Router + Webpack 5 | `next@pages/webpack` | Ready |
|
||||
| Vue | - | Coming soon |
|
||||
| Standalone | - | Coming soon |
|
||||
|
||||
|
||||
@@ -57,10 +57,10 @@ CLI для генерации SVG-спрайтов и типизированны
|
||||
|---|---|---|
|
||||
| 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` | Готово |
|
||||
| Next.js + App Router + Turbopack | `next@app/turbopack` | Готово |
|
||||
| Next.js + App Router + Webpack 5 | `next@app/webpack` | Готово |
|
||||
| Next.js + Pages Router + Turbopack | `next@pages/turbopack` | Готово |
|
||||
| Next.js + Pages Router + Webpack 5 | `next@pages/webpack` | Готово |
|
||||
| Vue | — | Скоро |
|
||||
| Standalone | — | Скоро |
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ A quick guide to generating centralized SVG sprites in `symbol` and `stack` form
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Prepare the icons and config
|
||||
@@ -37,10 +37,21 @@ export default defineLegacyConfig({
|
||||
})
|
||||
```
|
||||
|
||||
## 3. Run generation
|
||||
## 3. Add generation
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run the local package through the script:
|
||||
|
||||
```bash
|
||||
npx svg-sprites --mode legacy .
|
||||
npm run sprites
|
||||
```
|
||||
|
||||
Result:
|
||||
@@ -61,17 +72,6 @@ With `preview: false`, the HTML file is not created. For the `stack` format, spe
|
||||
</svg>
|
||||
```
|
||||
|
||||
## 5. Add a package script
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple sprites
|
||||
|
||||
Add multiple entries to `sprites`:
|
||||
|
||||
@@ -4,13 +4,21 @@
|
||||
|
||||
Version 1.0 separates local generation for React and Next.js from the centralized legacy mode. The old config cannot be mixed with the new API in a single CLI invocation.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the package as a development dependency so the migration uses the version recorded in the project lockfile:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## CLI
|
||||
|
||||
The CLI now always requires an explicit `--mode` and a path to the configuration directory:
|
||||
|
||||
```text
|
||||
svg-sprites
|
||||
→ svg-sprites --mode <mode> <path>
|
||||
"sprites": "svg-sprites"
|
||||
→ "sprites": "svg-sprites --mode <mode> <path>"
|
||||
```
|
||||
|
||||
Choose a mode based on your environment:
|
||||
@@ -40,6 +48,18 @@ export default defineNextSpriteConfig({
|
||||
|
||||
For regular React, use `defineReactSpriteConfig`. A folder and an explicit list of shared SVG files can be combined using `inputFolder` and `inputFiles`.
|
||||
|
||||
Add the local CLI with the selected mode to `package.json`, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:global": "svg-sprites --mode next@app/turbopack src/ui/global/svg-sprite"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run it with `npm run sprite:global` before importing the generated component.
|
||||
|
||||
The old `publicPath` and `react` options are no longer needed. The generated module is created next to the config and adds its own `.gitignore`, while Vite, Webpack, or Next.js emits the SVG as a separate asset with a content hash.
|
||||
|
||||
The `<SvgSprite icon="..." />` component is replaced by a component whose name is derived from `name`:
|
||||
@@ -76,12 +96,18 @@ export default defineLegacyConfig({
|
||||
- `loadConfig` has been replaced with `loadLegacyConfig`;
|
||||
- `publicPath` and generation of the old shared React component have been removed.
|
||||
|
||||
Run:
|
||||
Add the local CLI to `package.json`:
|
||||
|
||||
```bash
|
||||
svg-sprites --mode legacy .
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy ."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run it with `npm run sprites`.
|
||||
|
||||
## Programmatic API
|
||||
|
||||
The package is distributed as ESM only. Replace `require()` with `import`.
|
||||
@@ -90,7 +116,7 @@ The package is distributed as ESM only. Replace `require()` with `import`.
|
||||
|
||||
## After migration
|
||||
|
||||
1. Remove the old generated files and rules that ignored the entire directory containing the source icons.
|
||||
2. Add an explicit generation command before `dev`, `build`, and `typecheck`.
|
||||
3. Run generation and type checking.
|
||||
4. Check all icons and color variables using `SpriteViewer` or the legacy `preview.html`.
|
||||
1. Add an explicit generation command before `dev`, `build`, and `typecheck`.
|
||||
2. Generate the new output and run type checking while the old artifacts are still available.
|
||||
3. Replace imports and verify the icons and color variables using `SpriteViewer` or the legacy `preview.html`.
|
||||
4. Only then remove confirmed old generated files and obsolete ignore rules without deleting source SVGs.
|
||||
|
||||
@@ -4,15 +4,15 @@
|
||||
|
||||
Two explicit modes are supported:
|
||||
|
||||
| Bundler | Mode key | Next.js version |
|
||||
|---|---|---|
|
||||
| Turbopack | `next@app/turbopack` | 16.2+ |
|
||||
| Webpack 5 | `next@app/webpack` | 13.4+ |
|
||||
| Bundler | Mode key |
|
||||
|---|---|
|
||||
| Turbopack | `next@app/turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` |
|
||||
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Create a sprite module
|
||||
@@ -49,7 +49,13 @@ For Turbopack:
|
||||
}
|
||||
```
|
||||
|
||||
For Webpack, replace the mode key with `next@app/webpack`. In Next 13–15, Webpack is used with the regular `next build` command; in Next 16, use `next build --webpack`.
|
||||
For Webpack, replace the mode key with `next@app/webpack`.
|
||||
|
||||
Run the first generation before importing the generated module:
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
## 4. Use it in a Server Component
|
||||
|
||||
@@ -89,14 +95,10 @@ export default function SpritesPage() {
|
||||
|
||||
## Verify the bundler
|
||||
|
||||
```bash
|
||||
# Turbopack
|
||||
npx next build --turbopack
|
||||
Run the project's build script configured for the selected bundler:
|
||||
|
||||
# Webpack 5
|
||||
npx next build --webpack
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
For Next 13–15 with Webpack, use `npx next build` without the flag.
|
||||
|
||||
The Next.js command and the generator mode key must target the same bundler.
|
||||
The build script and the generator mode key must target the same bundler.
|
||||
|
||||
@@ -4,17 +4,15 @@
|
||||
|
||||
Two explicit modes are supported:
|
||||
|
||||
| Bundler | Mode key | Next.js version |
|
||||
|---|---|---|
|
||||
| Turbopack | `next@pages/turbopack` | 16.2+ |
|
||||
| Webpack 5 | `next@pages/webpack` | 12.2+ |
|
||||
|
||||
Next.js 12.2 requires React 18.
|
||||
| Bundler | Mode key |
|
||||
|---|---|
|
||||
| Turbopack | `next@pages/turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` |
|
||||
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Create a sprite module
|
||||
@@ -49,7 +47,13 @@ export default defineNextSpriteConfig({
|
||||
}
|
||||
```
|
||||
|
||||
For Next.js 16.2 with Turbopack, replace the mode key with `next@pages/turbopack`.
|
||||
For Turbopack, replace the mode key with `next@pages/turbopack`.
|
||||
|
||||
Run the first generation before importing the generated module:
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
## 4. Use it on a page
|
||||
|
||||
@@ -83,14 +87,10 @@ export default function SpritesPage() {
|
||||
|
||||
## Verify the bundler
|
||||
|
||||
```bash
|
||||
# Turbopack
|
||||
npx next build --turbopack
|
||||
Run the project's build script configured for the selected bundler:
|
||||
|
||||
# Webpack 5
|
||||
npx next build --webpack
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
For Next 12–15 with Webpack, use `npx next build` without the flag.
|
||||
|
||||
The Next.js command and the generator mode key must target the same bundler.
|
||||
The build script and the generator mode key must target the same bundler.
|
||||
|
||||
@@ -9,7 +9,7 @@ The result is a typed React component and a separate cacheable SVG asset.
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Create the sprite directory
|
||||
|
||||
@@ -9,7 +9,7 @@ The result is a typed React component and a separate SVG asset emitted through W
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Create the sprite directory
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
## 1. Установите пакет
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Подготовьте иконки и конфиг
|
||||
@@ -37,10 +37,21 @@ export default defineLegacyConfig({
|
||||
})
|
||||
```
|
||||
|
||||
## 3. Запустите генерацию
|
||||
## 3. Добавьте генерацию
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Запустите локально установленный пакет через script:
|
||||
|
||||
```bash
|
||||
npx svg-sprites --mode legacy .
|
||||
npm run sprites
|
||||
```
|
||||
|
||||
Результат:
|
||||
@@ -61,17 +72,6 @@ public/sprites/
|
||||
</svg>
|
||||
```
|
||||
|
||||
## 5. Добавьте package script
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Несколько спрайтов
|
||||
|
||||
Добавьте несколько записей в `sprites`:
|
||||
|
||||
@@ -4,13 +4,21 @@
|
||||
|
||||
Версия 1.0 разделяет локальную генерацию для React и Next.js и централизованный legacy-режим. Старый config нельзя смешивать с новым API в одном вызове CLI.
|
||||
|
||||
## Установка
|
||||
|
||||
Установите пакет как development dependency, чтобы миграция использовала версию из lockfile проекта:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## CLI
|
||||
|
||||
CLI теперь всегда требует явный `--mode` и путь к каталогу конфигурации:
|
||||
|
||||
```text
|
||||
svg-sprites
|
||||
→ svg-sprites --mode <mode> <path>
|
||||
"sprites": "svg-sprites"
|
||||
→ "sprites": "svg-sprites --mode <mode> <path>"
|
||||
```
|
||||
|
||||
Выберите mode по окружению:
|
||||
@@ -40,6 +48,18 @@ export default defineNextSpriteConfig({
|
||||
|
||||
Для обычного React используйте `defineReactSpriteConfig`. Папку и явный список общих SVG можно объединить через `inputFolder` и `inputFiles`.
|
||||
|
||||
Добавьте локальный CLI с выбранным mode в `package.json`, например:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:global": "svg-sprites --mode next@app/turbopack src/ui/global/svg-sprite"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Запустите его командой `npm run sprite:global` до импорта generated-компонента.
|
||||
|
||||
Старые `publicPath` и `react` больше не нужны. Generated-модуль создаётся рядом с конфигом, сам добавляет `.gitignore`, а Vite, Webpack или Next.js выпускает SVG как отдельный asset с content hash.
|
||||
|
||||
Компонент `<SvgSprite icon="..." />` заменяется компонентом, имя которого выводится из `name`:
|
||||
@@ -76,12 +96,18 @@ export default defineLegacyConfig({
|
||||
- `loadConfig` заменён на `loadLegacyConfig`;
|
||||
- `publicPath` и генерация старого общего React-компонента удалены.
|
||||
|
||||
Запуск:
|
||||
Добавьте локальный CLI в `package.json`:
|
||||
|
||||
```bash
|
||||
svg-sprites --mode legacy .
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy ."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Запустите его командой `npm run sprites`.
|
||||
|
||||
## Программный API
|
||||
|
||||
Пакет распространяется только как ESM. Замените `require()` на `import`.
|
||||
@@ -90,7 +116,7 @@ svg-sprites --mode legacy .
|
||||
|
||||
## После миграции
|
||||
|
||||
1. Удалите старые generated-файлы и правила, которые игнорировали целиком каталог с исходными иконками.
|
||||
2. Добавьте явную команду генерации перед `dev`, `build` и `typecheck`.
|
||||
3. Запустите генерацию и проверку типов.
|
||||
4. Проверьте все иконки и цветовые переменные через `SpriteViewer` или legacy `preview.html`.
|
||||
1. Добавьте явную команду генерации перед `dev`, `build` и `typecheck`.
|
||||
2. Создайте новый output и запустите проверку типов, пока старые artifacts остаются доступны.
|
||||
3. Замените imports и проверьте иконки и цветовые переменные через `SpriteViewer` или legacy `preview.html`.
|
||||
4. Только после этого удалите подтверждённые старые generated-файлы и устаревшие ignore rules, не затрагивая исходные SVG.
|
||||
|
||||
@@ -4,15 +4,15 @@
|
||||
|
||||
Поддерживаются два явных режима:
|
||||
|
||||
| Сборщик | Mode key | Версия Next.js |
|
||||
|---|---|---|
|
||||
| Turbopack | `next@app/turbopack` | 16.2+ |
|
||||
| Webpack 5 | `next@app/webpack` | 13.4+ |
|
||||
| Сборщик | Mode key |
|
||||
|---|---|
|
||||
| Turbopack | `next@app/turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` |
|
||||
|
||||
## 1. Установите пакет
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Создайте sprite-модуль
|
||||
@@ -49,7 +49,13 @@ export default defineNextSpriteConfig({
|
||||
}
|
||||
```
|
||||
|
||||
Для Webpack замените mode key на `next@app/webpack`. В Next 13–15 Webpack используется обычной командой `next build`, в Next 16 — командой `next build --webpack`.
|
||||
Для Webpack замените mode key на `next@app/webpack`.
|
||||
|
||||
До импорта generated-модуля выполните первую генерацию:
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
## 4. Используйте в Server Component
|
||||
|
||||
@@ -89,14 +95,10 @@ export default function SpritesPage() {
|
||||
|
||||
## Проверка сборщика
|
||||
|
||||
```bash
|
||||
# Turbopack
|
||||
npx next build --turbopack
|
||||
Запустите build script проекта, настроенный на выбранный сборщик:
|
||||
|
||||
# Webpack 5
|
||||
npx next build --webpack
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
Для Next 13–15 с Webpack используйте `npx next build` без флага.
|
||||
|
||||
Команда Next.js и mode key генератора должны указывать один и тот же сборщик.
|
||||
Build script и mode key генератора должны указывать один и тот же сборщик.
|
||||
|
||||
@@ -4,17 +4,15 @@
|
||||
|
||||
Поддерживаются два явных режима:
|
||||
|
||||
| Сборщик | Mode key | Версия Next.js |
|
||||
|---|---|---|
|
||||
| Turbopack | `next@pages/turbopack` | 16.2+ |
|
||||
| Webpack 5 | `next@pages/webpack` | 12.2+ |
|
||||
|
||||
Для Next.js 12.2 требуется React 18.
|
||||
| Сборщик | Mode key |
|
||||
|---|---|
|
||||
| Turbopack | `next@pages/turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` |
|
||||
|
||||
## 1. Установите пакет
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Создайте sprite-модуль
|
||||
@@ -49,7 +47,13 @@ export default defineNextSpriteConfig({
|
||||
}
|
||||
```
|
||||
|
||||
Для Next.js 16.2 с Turbopack замените mode key на `next@pages/turbopack`.
|
||||
Для Turbopack замените mode key на `next@pages/turbopack`.
|
||||
|
||||
До импорта generated-модуля выполните первую генерацию:
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
## 4. Используйте на странице
|
||||
|
||||
@@ -83,14 +87,10 @@ export default function SpritesPage() {
|
||||
|
||||
## Проверка сборщика
|
||||
|
||||
```bash
|
||||
# Turbopack
|
||||
npx next build --turbopack
|
||||
Запустите build script проекта, настроенный на выбранный сборщик:
|
||||
|
||||
# Webpack 5
|
||||
npx next build --webpack
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
Для Next 12–15 с Webpack используйте `npx next build` без флага.
|
||||
|
||||
Команда Next.js и mode key генератора должны указывать один и тот же сборщик.
|
||||
Build script и mode key генератора должны указывать один и тот же сборщик.
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
## 1. Установите пакет
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Создайте папку спрайта
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
## 1. Установите пакет
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
## 2. Создайте папку спрайта
|
||||
|
||||
@@ -12,4 +12,4 @@ The package supports multiple independent sprites in one project. Each selected
|
||||
|
||||
The project determines how many sprite directories exist and where they live. For example, `name: 'file-manager'` produces `FileManagerIcon`, while another directory with `name: 'navigation'` produces a separate `NavigationIcon`. The names `FileManagerIcon` and `fileManagerIconNames` used below are examples of the API for one possible sprite, not fixed package exports.
|
||||
|
||||
Generated production components do not import `@gromlab/svg-sprites` at runtime. For routine generation, run the latest CLI through `npx`; install the package in the project only when `SpriteViewer`, the programmatic API, or a local config helper is required.
|
||||
Generated production components do not import `@gromlab/svg-sprites` at runtime. Install the package as a development dependency so configuration helpers and the local CLI use the version recorded in the project's lockfile.
|
||||
|
||||
@@ -12,10 +12,14 @@ Select exactly one supported mode key:
|
||||
| Next.js Pages Router + Webpack 5 | `next@pages/webpack` |
|
||||
| Existing shared config | `legacy` |
|
||||
|
||||
Do not use the incomplete `react`, `next@app`, or `next@pages` keys, the future `standalone` mode, or a mode for a different bundler. The CLI always requires a mode and exactly one path to a configuration directory:
|
||||
Do not use the incomplete `react`, `next@app`, or `next@pages` keys, the future `standalone` mode, or a mode for a different bundler. Install the package as a development dependency and add the local CLI to a package script. The CLI always requires a mode and exactly one path to a configuration directory:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode <mode-key> <sprite-directory>
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:<name>": "svg-sprites --mode <mode-key> <sprite-directory>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Do not pass multiple paths, a glob, or the path to the config file itself. For multiple modern sprites, create a separate command for each directory.
|
||||
|
||||
@@ -12,18 +12,26 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
One `svg-sprite.config.ts` creates one independent sprite. For multiple sets, choose multiple directories and assign each a unique `name`.
|
||||
|
||||
When running through `npx`, the config may export a plain object without importing the package:
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Use the configuration helper for autocomplete and type checking:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../shared/icons/close.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The object contract is the same for React and Next.js. If the package is already installed, the object may be wrapped in `defineReactSpriteConfig(...)` or `defineNextSpriteConfig(...)` for autocomplete. A helper is not required for normal CLI generation.
|
||||
The object contract is the same for React and Next.js. Use `defineNextSpriteConfig(...)` instead for a Next.js sprite.
|
||||
|
||||
`name` must begin with an ASCII letter and use kebab-case. The example `file-manager` produces `FileManagerIcon`, `FileManagerIconName`, and `fileManagerIconNames`. Another sprite gets its own names. If `name` is omitted, the generator derives it from the directory.
|
||||
|
||||
@@ -32,7 +40,7 @@ Add a separate command with the selected mode key and one path:
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprites": "npm run sprite:file-manager"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,4 +70,4 @@ Automatic replacement targets `fill`/`stroke` attributes and inline `style`. The
|
||||
- in Webpack, pass an array of static `() => import('.../manifest')` loaders;
|
||||
- in Next.js, use the same static loaders, and for the App Router put the Viewer in a separate file with `'use client'`.
|
||||
|
||||
The Viewer accepts manifests/loaders and provides search, themes, colors, and examples, but production components do not depend on it. To import `@gromlab/svg-sprites/react`, install the package using the project's package manager.
|
||||
The Viewer accepts manifests/loaders and provides search, themes, colors, and examples, but production components do not depend on it. Import it from the package already installed as a development dependency.
|
||||
|
||||
@@ -5,7 +5,7 @@ After changing a config or SVG, perform these required quick checks:
|
||||
1. Run the exact sprite command, for example `npm run sprite:file-manager`; it must exit with code `0` and report the name, icon count, mode, and `generated` directory.
|
||||
2. Confirm that `index.ts`, `manifest.ts`, `generated/sprite.svg`, `generated/react-component.tsx`, `generated/types.ts`, `generated/styles.module.css`, and `generated/.svg-sprites.manifest.json` exist.
|
||||
3. Confirm that the new icon appears in the readonly name array and is accepted by the `icon` prop.
|
||||
4. Run the project's existing type check, for example `npm run typecheck` or `npx tsc --noEmit`.
|
||||
4. Run the project's existing type check, for example `npm run typecheck`.
|
||||
5. Check that `target` in `manifest.ts` matches the selected mode key; the generated asset expression must use `?no-inline` for Vite and `new URL(...)` for Webpack/Next.
|
||||
|
||||
Do not run a full production build solely to verify a changed icon list. It is required when the bundler target, asset pipeline configuration, Next router/bundler, or Webpack loader changed, or when diagnosing a runtime URL failure.
|
||||
|
||||
@@ -9,10 +9,10 @@ Use this document when a source contains `<defs>`, gradients, patterns, filters,
|
||||
Inspect the source SVG before editing it:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
Replace the mode and path with the actual values. Then compare the source with `generated/sprite.svg` and the manifest; do not draw conclusions from a successful exit code alone.
|
||||
Use the actual package script for the sprite. Then compare the source with `generated/sprite.svg` and the manifest; do not draw conclusions from a successful exit code alone.
|
||||
|
||||
Pay particular attention to:
|
||||
|
||||
@@ -36,17 +36,19 @@ The compiler first applies SVGO `preset-default` while preserving `viewBox`, the
|
||||
All three options default to `true` and apply to the entire sprite, not to individual icons.
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'illustrations',
|
||||
transform: {
|
||||
removeSize: false,
|
||||
replaceColors: false,
|
||||
addTransition: false,
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
This is a plain config for one of potentially many sprite directories in a project; its directory does not have to match a module/feature directory. Use the same `transform` for Next; in legacy mode it belongs at the top level of the config. When the package is installed locally for SpriteViewer or the programmatic API, the object may optionally be wrapped in the appropriate `define*Config(...)` helper.
|
||||
This is a config for one of potentially many sprite directories in a project; its directory does not have to match a module/feature directory. Use `defineNextSpriteConfig(...)` with the same `transform` for Next; in legacy mode it belongs at the top level of `defineLegacyConfig(...)`.
|
||||
|
||||
## Dimensions and viewBox
|
||||
|
||||
|
||||
@@ -15,10 +15,18 @@ Use this document when the project already has a root `svg-sprites.config.ts`, c
|
||||
|
||||
## Config and execution
|
||||
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
`svg-sprites.config.ts`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineLegacyConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineLegacyConfig({
|
||||
output: 'public/sprites',
|
||||
preview: true,
|
||||
transform: {
|
||||
@@ -41,28 +49,24 @@ export default {
|
||||
format: 'stack',
|
||||
},
|
||||
],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The package does not need to be installed for normal CLI use. If it is installed locally for the programmatic API, the config may optionally be wrapped in `defineLegacyConfig(...)` for autocomplete. Unlike local React/Next configs, each of which describes one of potentially many sprites, a single legacy config retains the specific ability to manage one or more sprite entries.
|
||||
|
||||
Run from the project root:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode legacy .
|
||||
```
|
||||
Unlike local React/Next configs, each of which describes one of potentially many sprites, a single legacy config retains the specific ability to manage one or more sprite entries.
|
||||
|
||||
Script:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "npx --yes @gromlab/svg-sprites@latest --mode legacy .",
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run `npm run sprites` from the project root.
|
||||
|
||||
The CLI path points to the directory containing `svg-sprites.config.ts`. Do not pass the file itself. For a config in another directory, pass that directory explicitly.
|
||||
|
||||
## Input semantics
|
||||
@@ -116,7 +120,7 @@ Run a production build and browser/Network checks additionally only when the out
|
||||
## Common failures
|
||||
|
||||
- `Config file not found`: the CLI path is not a directory containing `svg-sprites.config.ts`.
|
||||
- `Config file must have a default export`: add plain `export default { ... }`; a locally installed helper is optional.
|
||||
- `Config file must have a default export`: export the config through `defineLegacyConfig(...)`.
|
||||
- Deprecated `mode`: the `sprites[].mode` field was renamed to `format`.
|
||||
- `sprites must be a non-empty array`: a legacy config cannot be empty.
|
||||
- `Input directory does not exist` or `SVG file does not exist`: remember that paths are resolved from the config directory when loaded by the CLI.
|
||||
|
||||
@@ -10,13 +10,12 @@ First record the project's current contract:
|
||||
|
||||
```bash
|
||||
npm ls @gromlab/svg-sprites
|
||||
npx --yes @gromlab/svg-sprites@latest --help
|
||||
```
|
||||
|
||||
If this is an actual migration of imports, config helpers, or the programmatic API, install the current package locally. Installation is unnecessary for CLI generation alone:
|
||||
Install the current package as a development dependency before updating the config and scripts:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Find and read:
|
||||
@@ -41,10 +40,12 @@ API mapping:
|
||||
| `sprites[].mode` | `sprites[].format` |
|
||||
| `generate` | `generateLegacy` |
|
||||
| `loadConfig` | `loadLegacyConfig` |
|
||||
| CLI without mode | `npx --yes @gromlab/svg-sprites@latest --mode legacy <config-dir>` |
|
||||
| CLI without mode | `svg-sprites --mode legacy <config-dir>` in a package script |
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineLegacyConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineLegacyConfig({
|
||||
output: 'public/sprites',
|
||||
preview: true,
|
||||
sprites: [
|
||||
@@ -54,12 +55,18 @@ export default {
|
||||
format: 'symbol',
|
||||
},
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy ."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode legacy .
|
||||
```
|
||||
Run it with `npm run sprites`.
|
||||
|
||||
`publicPath` and generation of the old shared React component were removed. If the application used that component, legacy mode preserves the SVG asset, but the React wrapper must be replaced separately. The complete legacy workflow is in [legacy.md](legacy.md).
|
||||
|
||||
@@ -70,14 +77,16 @@ Choose this path when typed components, bundler-hashed assets, Server Components
|
||||
For each required sprite, create a project directory with local `svg-sprite.config.ts` and, when using a folder, `icons/`. The directory does not have to be a module/feature directory; each config describes one of potentially many sprites:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'global',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
When the package is installed locally, the object may optionally be wrapped in `defineReactSpriteConfig(...)` or, for Next.js, `defineNextSpriteConfig(...)`. Then select exactly one mode:
|
||||
For Next.js, use `defineNextSpriteConfig(...)` instead. Then select exactly one mode:
|
||||
|
||||
| Environment | Mode |
|
||||
|---|---|
|
||||
@@ -90,10 +99,17 @@ When the package is installed locally, the object may optionally be wrapped in `
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/global/svg-sprite
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:global": "svg-sprites --mode react@vite src/ui/global/svg-sprite",
|
||||
"sprites": "npm run sprite:global"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run it with `npm run sprite:global`.
|
||||
|
||||
Replace the old generic component:
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -6,12 +6,12 @@ Use this document when the application uses `app/` or `src/app/` and needs a gen
|
||||
|
||||
## Target matrix
|
||||
|
||||
| Bundler | CLI mode | Minimum Next.js version | Conditional verification build |
|
||||
|---|---|---:|---|
|
||||
| Turbopack | `next@app/turbopack` | 16.2 | `npx next build --turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` | 13.4 | Next 13-15: `npx next build`; Next 16: `npx next build --webpack` |
|
||||
| Bundler | CLI mode |
|
||||
|---|---|
|
||||
| Turbopack | `next@app/turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` |
|
||||
|
||||
Do not infer the target only from the presence of `next.config.*`. Check the installed Next.js version and the actual flags in `dev`/`build`. The generator mode and verification-build bundler must agree.
|
||||
Do not infer the target only from the presence of `next.config.*`. Check the actual flags in `dev`/`build`. The generator mode and verification-build bundler must agree.
|
||||
|
||||
## Prepare the sprite directory
|
||||
|
||||
@@ -23,16 +23,23 @@ src/ui/file-manager/svg-sprite/
|
||||
└── svg-sprite.config.ts
|
||||
```
|
||||
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineNextSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineNextSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
- The package does not need to be installed for normal CLI generation. When installed locally for SpriteViewer or the programmatic API, the object may optionally be wrapped in `defineNextSpriteConfig(...)` for autocomplete.
|
||||
- The project chooses the directory for each specific sprite; it does not have to be a module/feature directory. Each config describes one of potentially many application sprites.
|
||||
- The config filename is singular: `svg-sprite.config.ts`.
|
||||
- Paths are relative to its directory; `inputFolder` scanning is shallow.
|
||||
@@ -44,24 +51,12 @@ export default {
|
||||
|
||||
## Generation
|
||||
|
||||
For Turbopack:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@app/turbopack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
For Webpack 5:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@app/webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Example scripts for Turbopack:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode next@app/turbopack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode next@app/turbopack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -69,7 +64,7 @@ Example scripts for Turbopack:
|
||||
}
|
||||
```
|
||||
|
||||
For Webpack, replace only the complete mode with `next@app/webpack`. Do not run both targets sequentially for one directory: the second generation overwrites the first target's files.
|
||||
For Webpack, replace only the complete mode with `next@app/webpack`. Do not run both targets sequentially for one directory: the second generation overwrites the first target's files. Run `npm run sprite:file-manager` for the first generation.
|
||||
|
||||
## Server Component
|
||||
|
||||
@@ -95,12 +90,6 @@ Do not import from `generated/` or move the SVG into `public`. Managed files (`g
|
||||
|
||||
The Viewer is interactive and imported from a client-only entry. Create a separate Client Component page or child component:
|
||||
|
||||
Install the package locally for the Viewer:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
|
||||
@@ -124,23 +113,15 @@ Start with generation and typechecking:
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
npx tsc --noEmit
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
If the target or Next build/deployment pipeline changed, or a runtime issue is being diagnosed, then run exactly one production build matching the target:
|
||||
If the target or Next build/deployment pipeline changed, or a runtime issue is being diagnosed, run the project's production build configured for the selected bundler:
|
||||
|
||||
```bash
|
||||
npx next build --turbopack
|
||||
npm run build
|
||||
```
|
||||
|
||||
or:
|
||||
|
||||
```bash
|
||||
npx next build --webpack
|
||||
```
|
||||
|
||||
For Webpack on Next 13-15, use `npx next build` without a flag.
|
||||
|
||||
After the required generation and typecheck, verify that:
|
||||
|
||||
- `manifest.ts` contains the exact target `next@app/turbopack` or `next@app/webpack`;
|
||||
@@ -157,7 +138,7 @@ During a conditional production/runtime check, also verify that:
|
||||
|
||||
- `Next.js mode requires a router and bundler`: `--mode next` is invalid; specify the full mode.
|
||||
- Build passes with one bundler but the runtime asset breaks with another: regenerate for the target actually used by the build.
|
||||
- Webpack was selected on Next 16, but the build used Turbopack: use `next build --webpack` and `next@app/webpack`.
|
||||
- Webpack was selected, but the build used Turbopack: use the project's Webpack build command and `next@app/webpack`.
|
||||
- Viewer causes a Server Component error: the Viewer file needs `'use client'`; the generated icon component does not.
|
||||
- `React config file not found`: the command received the path to `app/`, `icons/`, or the config file instead of the sprite directory.
|
||||
- Two CI jobs generate different targets in one checkout: separate their directories or ensure each job uses one consistent target.
|
||||
|
||||
@@ -6,12 +6,12 @@ Use this document for pages under `pages/` or `src/pages/`, including SSR with `
|
||||
|
||||
## Selecting a target
|
||||
|
||||
| Bundler | CLI mode | Minimum Next.js version | Conditional build check |
|
||||
|---|---|---:|---|
|
||||
| Turbopack | `next@pages/turbopack` | 16.2 | `npx next build --turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` | 12.2 | Next 12-15: `npx next build`; Next 16: `npx next build --webpack` |
|
||||
| Bundler | CLI mode |
|
||||
|---|---|
|
||||
| Turbopack | `next@pages/turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` |
|
||||
|
||||
Next.js 12.2 requires React 18. Determine the installed version and the actual script flags before selecting a mode. The presence of the Pages Router does not automatically imply Webpack: Next 16.2 supports Turbopack.
|
||||
Determine the actual script flags before selecting a mode. The presence of the Pages Router does not automatically imply Webpack; select the target from the bundler used by the project.
|
||||
|
||||
## Structure and config
|
||||
|
||||
@@ -23,16 +23,24 @@ src/ui/file-manager/svg-sprite/
|
||||
└── svg-sprite.config.ts
|
||||
```
|
||||
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineNextSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineNextSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The package does not need to be installed for normal CLI generation. When installed locally for SpriteViewer or the programmatic API, the config may optionally be wrapped in `defineNextSpriteConfig(...)` for autocomplete. The project chooses the directory containing each specific sprite config, and it does not have to be a module/feature directory; each config describes one of potentially many application sprites.
|
||||
The project chooses the directory containing each specific sprite config, and it does not have to be a module/feature directory; each config describes one of potentially many application sprites.
|
||||
|
||||
All source paths are resolved from the config directory. `inputFolder` defaults to `./icons`, and scanning is shallow. `inputFiles` is merged with the folder. The same path is deduplicated, but two different `check.svg` files conflict. An explicitly configured missing folder is an error even when `inputFiles` is non-empty.
|
||||
|
||||
@@ -40,24 +48,12 @@ All source paths are resolved from the config directory. `inputFolder` defaults
|
||||
|
||||
## Commands
|
||||
|
||||
Webpack 5:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@pages/webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Turbopack:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@pages/turbopack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Example lifecycle scripts for Webpack:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode next@pages/webpack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode next@pages/webpack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -65,7 +61,7 @@ Example lifecycle scripts for Webpack:
|
||||
}
|
||||
```
|
||||
|
||||
If pre-scripts already exist, add generation to their current command chain. Generated imports are absent from Git, so generation must precede TypeScript and Next compilation.
|
||||
If pre-scripts already exist, add generation to their current command chain. Generated imports are absent from Git, so generation must precede TypeScript and Next compilation. For Turbopack, replace the complete mode with `next@pages/turbopack`. Run `npm run sprite:file-manager` for the first generation.
|
||||
|
||||
## Usage in the Pages Router
|
||||
|
||||
@@ -89,12 +85,6 @@ Import the component and types only from the local `svg-sprite/index.ts`. Do not
|
||||
|
||||
Pages Router components run on the client as well, so a separate `'use client'` directive is unnecessary:
|
||||
|
||||
Install the package locally for SpriteViewer:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
@@ -114,23 +104,15 @@ Use literal imports and expose the page only as a debug/internal tool. If the pa
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
npx tsc --noEmit
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
If the target or Next build/deployment pipeline changed, or a runtime issue is being diagnosed, run a production build for the selected bundler:
|
||||
If the target or Next build/deployment pipeline changed, or a runtime issue is being diagnosed, run the project's production build configured for the selected bundler:
|
||||
|
||||
```bash
|
||||
npx next build --turbopack
|
||||
npm run build
|
||||
```
|
||||
|
||||
or, for Webpack on Next 16:
|
||||
|
||||
```bash
|
||||
npx next build --webpack
|
||||
```
|
||||
|
||||
For Webpack on Next 12-15, run `npx next build`.
|
||||
|
||||
After the required generation and typecheck, verify that:
|
||||
|
||||
- `manifest.ts` contains `next@pages/turbopack` or `next@pages/webpack`;
|
||||
@@ -146,8 +128,7 @@ After the conditional production build, and only when browser tools are availabl
|
||||
## Common failures
|
||||
|
||||
- Mode uses `next@app/...`: the module may generate, but its manifest and target contract are wrong; use `next@pages/...`.
|
||||
- On Next 16, the command and mode select different bundlers: add the matching build flag and regenerate.
|
||||
- Next 12.2 uses React 17: upgrade React to 18 before diagnosing the sprite runtime.
|
||||
- The command and mode select different bundlers: use the project's matching build command and regenerate.
|
||||
- Viewer manifest is missing from the chunk: the `import()` path must be a string literal and must exist before the Next build.
|
||||
- Icon appears after a full reload but disappears during navigation: check external asset availability with `basePath`, `assetPrefix`, and the production origin.
|
||||
- `Refusing to overwrite a user file`: the sprite directory contains an unmanaged file with a reserved name; move it.
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
## Required installation
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Programmatic imports require a local dependency; `npx` does not replace it. This reference always describes the package's latest API.
|
||||
Programmatic imports require the local development dependency shown above. This reference describes the installed package API.
|
||||
|
||||
## When to use this reference
|
||||
|
||||
|
||||
@@ -23,18 +23,25 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
## Setup
|
||||
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
`src/ui/file-manager/svg-sprite/svg-sprite.config.ts`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
- The package does not need to be installed for normal CLI generation. If it is already installed locally for SpriteViewer or the programmatic API, `defineReactSpriteConfig(...)` may be used as an optional autocomplete helper.
|
||||
- Each config describes one specific sprite; an application may contain many independent configs and sprites.
|
||||
- Every config path is resolved relative to the directory containing `svg-sprite.config.ts`.
|
||||
- `inputFolder` defaults to `./icons`; folder scanning is shallow and includes files ending in `.svg`.
|
||||
@@ -46,18 +53,12 @@ export default {
|
||||
|
||||
## Command and scripts
|
||||
|
||||
Exact command for the example above:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Add it to `package.json` and run it before processes that need generated imports:
|
||||
Add the local CLI to `package.json` and run it before processes that need generated imports:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -67,6 +68,8 @@ Add it to `package.json` and run it before processes that need generated imports
|
||||
|
||||
If the project already has `predev` or `prebuild`, integrate generation into the existing orchestration instead of overwriting the script.
|
||||
|
||||
Run `npm run sprite:file-manager` for the first generation.
|
||||
|
||||
## Usage
|
||||
|
||||
Import only from the public local entry point:
|
||||
@@ -118,11 +121,7 @@ A manual `#check` fragment is safe only for names matching `^[a-zA-Z][a-zA-Z0-9_
|
||||
|
||||
## SpriteViewer
|
||||
|
||||
After generation, install the package if needed and add the Viewer only to a debug route:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
After generation, add the Viewer only to a debug route:
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
@@ -23,31 +23,33 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
## Configuration and generation
|
||||
|
||||
Install the package as a development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'File manager icons',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The package does not need to be installed for normal CLI generation. When installed locally for SpriteViewer or the programmatic API, the config may optionally be wrapped in `defineReactSpriteConfig(...)` for autocomplete. Each config describes one of potentially many independent application sprites.
|
||||
Each config describes one of potentially many independent application sprites.
|
||||
|
||||
Paths are relative to `svg-sprite.config.ts`. The folder is scanned only at its top level. `inputFolder` and `inputFiles` are merged; duplicate paths are deduplicated, but equal basenames from different files cause an ID conflict. The implicit `./icons` folder may be absent when `inputFiles` is non-empty; an explicitly configured missing folder is an error. `FileManagerIcon` below is only an example generated name for `name: 'file-manager'`.
|
||||
|
||||
Exact command:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Recommended lifecycle hooks:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@webpack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@webpack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -55,7 +57,7 @@ Recommended lifecycle hooks:
|
||||
}
|
||||
```
|
||||
|
||||
Do not overwrite existing pre-scripts; add generation to their current command chain. The React preset always emits `stack`.
|
||||
Do not overwrite existing pre-scripts; add generation to their current command chain. Run `npm run sprite:file-manager` for the first generation. The React preset always emits `stack`.
|
||||
|
||||
## Public component
|
||||
|
||||
@@ -105,12 +107,6 @@ Integrate this rule with the project's current configuration; do not add a dupli
|
||||
|
||||
Webpack does not provide `import.meta.glob`. Pass static lazy imports with string-literal paths:
|
||||
|
||||
SpriteViewer requires the package to be installed locally:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
|
||||
@@ -12,4 +12,4 @@
|
||||
|
||||
Количество и расположение каталогов определяет проект. Например, `name: 'file-manager'` создаёт `FileManagerIcon`, а другой каталог с `name: 'navigation'` создаст отдельный `NavigationIcon`. Имена `FileManagerIcon` и `fileManagerIconNames` ниже являются примерами API одного из возможных спрайтов, а не фиксированными экспортами пакета.
|
||||
|
||||
Generated production-компоненты не импортируют `@gromlab/svg-sprites` во время выполнения. Для обычной генерации запускай latest CLI через `npx`; устанавливай пакет в проект, только если нужен `SpriteViewer`, программный API или локальный config helper.
|
||||
Generated production-компоненты не импортируют `@gromlab/svg-sprites` во время выполнения. Устанавливай пакет как development dependency, чтобы config helpers и локальный CLI использовали версию из lockfile проекта.
|
||||
|
||||
@@ -12,10 +12,14 @@
|
||||
| Next.js Pages Router + Webpack 5 | `next@pages/webpack` |
|
||||
| Старый общий конфиг | `legacy` |
|
||||
|
||||
Не используй неполные `react`, `next@app`, `next@pages`, будущий `standalone` или mode другого сборщика. CLI всегда требует mode и ровно один путь к каталогу конфигурации:
|
||||
Не используй неполные `react`, `next@app`, `next@pages`, будущий `standalone` или mode другого сборщика. Установи пакет как development dependency и добавь локальный CLI в package script. CLI всегда требует mode и ровно один путь к каталогу конфигурации:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode <mode-key> <sprite-directory>
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:<name>": "svg-sprites --mode <mode-key> <sprite-directory>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Не передавай несколько путей, glob или путь к самому файлу конфигурации. Для нескольких современных спрайтов создай отдельную команду для каждого каталога.
|
||||
|
||||
@@ -12,18 +12,26 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
Один `svg-sprite.config.ts` создаёт один независимый спрайт. Для нескольких наборов выбери несколько каталогов и дай каждому уникальное `name`.
|
||||
|
||||
Для запуска через `npx` конфиг может экспортировать обычный объект без импорта пакета:
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Используй config helper для autocomplete и проверки типов:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../shared/icons/close.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Контракт объекта одинаков для React и Next.js. Если пакет уже установлен, объект можно обернуть в `defineReactSpriteConfig(...)` или `defineNextSpriteConfig(...)` ради autocomplete. Для обычной CLI-генерации helper не обязателен.
|
||||
Контракт объекта одинаков для React и Next.js. Для Next.js-спрайта используй `defineNextSpriteConfig(...)`.
|
||||
|
||||
`name` должен начинаться с латинской буквы и записываться в kebab-case; из примера `file-manager` будут созданы `FileManagerIcon`, `FileManagerIconName` и `fileManagerIconNames`. Другой спрайт получает собственные имена. Если `name` не задан, генератор выводит его из каталога.
|
||||
|
||||
@@ -32,7 +40,7 @@ export default {
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprites": "npm run sprite:file-manager"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,4 +70,4 @@ Generated-компонент не выбирает семантику за пр
|
||||
- в Webpack передай массив статических `() => import('.../manifest')`;
|
||||
- в Next.js используй такие же статические loaders, а для App Router помести Viewer в отдельный файл с `'use client'`.
|
||||
|
||||
Viewer принимает manifests/loaders, показывает поиск, темы, цвета и примеры, но production-компоненты от него не зависят. Чтобы импортировать `@gromlab/svg-sprites/react`, установи пакет в проект подходящим для его package manager способом.
|
||||
Viewer принимает manifests/loaders, показывает поиск, темы, цвета и примеры, но production-компоненты от него не зависят. Импортируй его из пакета, уже установленного как development dependency.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
1. Запусти точную sprite-команду, например `npm run sprite:file-manager`; процесс должен завершиться с кодом `0` и сообщить имя, число иконок, mode и каталог `generated`.
|
||||
2. Проверь наличие `index.ts`, `manifest.ts`, `generated/sprite.svg`, `generated/react-component.tsx`, `generated/types.ts`, `generated/styles.module.css` и `generated/.svg-sprites.manifest.json`.
|
||||
3. Убедись, что новая иконка присутствует в readonly-массиве имён и принимается prop `icon`.
|
||||
4. Запусти существующую проверку типов проекта, например `npm run typecheck` или `npx tsc --noEmit`.
|
||||
4. Запусти существующую проверку типов проекта, например `npm run typecheck`.
|
||||
5. Проверь в `manifest.ts`, что `target` совпадает с выбранным mode key; generated asset expression должен быть `?no-inline` для Vite и `new URL(...)` для Webpack/Next.
|
||||
|
||||
Не запускай полную production-сборку только ради проверки изменения списка иконок. Она нужна, если менялся bundler target, конфигурация asset pipeline, Next router/bundler, Webpack loader или диагностируется ошибка URL в runtime.
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
Проверь исходный SVG до редактирования:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite
|
||||
npm run sprite:file-manager
|
||||
```
|
||||
|
||||
Замени mode и path на фактические. Затем сравни source с `generated/sprite.svg` и manifest, не делая вывод только по успешному exit code.
|
||||
Используй фактический package script нужного спрайта. Затем сравни source с `generated/sprite.svg` и manifest, не делая вывод только по успешному exit code.
|
||||
|
||||
Особого внимания требуют:
|
||||
|
||||
@@ -36,17 +36,19 @@ npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-
|
||||
Все три опции по умолчанию `true` и применяются ко всему спрайту, не к отдельной иконке.
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'illustrations',
|
||||
transform: {
|
||||
removeSize: false,
|
||||
replaceColors: false,
|
||||
addTransition: false,
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Это plain config для одного из потенциально многих проектов спрайтов; его каталог не обязан совпадать с module/feature-каталогом. Для Next используй тот же `transform`; для legacy он находится на верхнем уровне config. При локальной установке пакета ради SpriteViewer или программного API объект можно опционально обернуть в подходящий `define*Config(...)` helper.
|
||||
Это config для одного из потенциально многих проектов спрайтов; его каталог не обязан совпадать с module/feature-каталогом. Для Next используй `defineNextSpriteConfig(...)` с тем же `transform`; для legacy он находится на верхнем уровне `defineLegacyConfig(...)`.
|
||||
|
||||
## Размеры и viewBox
|
||||
|
||||
|
||||
@@ -15,10 +15,18 @@
|
||||
|
||||
## Конфиг и запуск
|
||||
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
`svg-sprites.config.ts`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineLegacyConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineLegacyConfig({
|
||||
output: 'public/sprites',
|
||||
preview: true,
|
||||
transform: {
|
||||
@@ -41,28 +49,24 @@ export default {
|
||||
format: 'stack',
|
||||
},
|
||||
],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Для обычного CLI пакет устанавливать не нужно. Если он установлен локально ради программного API, config можно опционально обернуть в `defineLegacyConfig(...)` для autocomplete. В отличие от локальных React/Next config, каждый из которых описывает один из потенциально многих спрайтов, один legacy config сохраняет специфическую возможность управлять одним или несколькими entries спрайтов.
|
||||
|
||||
Запуск из project root:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode legacy .
|
||||
```
|
||||
В отличие от локальных React/Next config, каждый из которых описывает один из потенциально многих спрайтов, один legacy config сохраняет специфическую возможность управлять одним или несколькими entries спрайтов.
|
||||
|
||||
Script:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "npx --yes @gromlab/svg-sprites@latest --mode legacy .",
|
||||
"sprites": "svg-sprites --mode legacy .",
|
||||
"prebuild": "npm run sprites"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Запусти `npm run sprites` из project root.
|
||||
|
||||
CLI path указывает каталог с `svg-sprites.config.ts`. Не передавай сам файл. Для config в другом каталоге передай этот каталог явно.
|
||||
|
||||
## Семантика input
|
||||
@@ -116,7 +120,7 @@ Production build и браузер/Network запускай дополнител
|
||||
## Типовые ошибки
|
||||
|
||||
- `Config file not found`: CLI path не является каталогом с `svg-sprites.config.ts`.
|
||||
- `Config file must have a default export`: добавь plain `export default { ... }`; локально установленный helper здесь необязателен.
|
||||
- `Config file must have a default export`: экспортируй config через `defineLegacyConfig(...)`.
|
||||
- Deprecated `mode`: поле `sprites[].mode` переименовано в `format`.
|
||||
- `sprites must be a non-empty array`: legacy config не допускает пустую конфигурацию.
|
||||
- `Input directory does not exist` или `SVG file does not exist`: помни, что paths считаются от каталога config при загрузке CLI.
|
||||
|
||||
@@ -10,13 +10,12 @@
|
||||
|
||||
```bash
|
||||
npm ls @gromlab/svg-sprites
|
||||
npx --yes @gromlab/svg-sprites@latest --help
|
||||
```
|
||||
|
||||
Если это реальная миграция импортов, config helpers или программного API, установи актуальный пакет локально. Для одной только CLI-генерации установка не нужна:
|
||||
Перед обновлением config и scripts установи актуальный пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Найди и прочитай:
|
||||
@@ -41,10 +40,12 @@ npm install @gromlab/svg-sprites@latest
|
||||
| `sprites[].mode` | `sprites[].format` |
|
||||
| `generate` | `generateLegacy` |
|
||||
| `loadConfig` | `loadLegacyConfig` |
|
||||
| CLI без mode | `npx --yes @gromlab/svg-sprites@latest --mode legacy <config-dir>` |
|
||||
| CLI без mode | `svg-sprites --mode legacy <config-dir>` в package script |
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineLegacyConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineLegacyConfig({
|
||||
output: 'public/sprites',
|
||||
preview: true,
|
||||
sprites: [
|
||||
@@ -54,12 +55,18 @@ export default {
|
||||
format: 'symbol',
|
||||
},
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprites": "svg-sprites --mode legacy ."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode legacy .
|
||||
```
|
||||
Запусти его командой `npm run sprites`.
|
||||
|
||||
`publicPath` и генерация старого общего React-компонента удалены. Если приложение использовало этот компонент, legacy сохранит SVG asset, но React wrapper придётся заменить отдельно. Полный legacy workflow находится в [legacy.md](legacy.md).
|
||||
|
||||
@@ -70,14 +77,16 @@ npx --yes @gromlab/svg-sprites@latest --mode legacy .
|
||||
Для каждого нужного спрайта создай каталог проекта с локальным `svg-sprite.config.ts` и, при использовании папки, `icons/`. Каталог не обязан быть module/feature-каталогом; каждый config описывает один из потенциально многих спрайтов:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'global',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
При локальной установке package объект можно опционально обернуть в `defineReactSpriteConfig(...)` или, для Next.js, `defineNextSpriteConfig(...)`. Затем выбери ровно один mode:
|
||||
Для Next.js используй `defineNextSpriteConfig(...)`. Затем выбери ровно один mode:
|
||||
|
||||
| Среда | Mode |
|
||||
|---|---|
|
||||
@@ -90,10 +99,17 @@ export default {
|
||||
|
||||
Пример:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/global/svg-sprite
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:global": "svg-sprites --mode react@vite src/ui/global/svg-sprite",
|
||||
"sprites": "npm run sprite:global"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Запусти его командой `npm run sprite:global`.
|
||||
|
||||
Замени старый generic component:
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
## Матрица target
|
||||
|
||||
| Сборщик | CLI mode | Минимальная версия Next.js | Команда условной контрольной сборки |
|
||||
|---|---|---:|---|
|
||||
| Turbopack | `next@app/turbopack` | 16.2 | `npx next build --turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` | 13.4 | Next 13-15: `npx next build`; Next 16: `npx next build --webpack` |
|
||||
| Сборщик | CLI mode |
|
||||
|---|---|
|
||||
| Turbopack | `next@app/turbopack` |
|
||||
| Webpack 5 | `next@app/webpack` |
|
||||
|
||||
Не выводи target только из наличия `next.config.*`. Проверь установленную версию Next.js и фактические flags в `dev`/`build`. Mode генератора и сборщик контрольной сборки должны совпадать.
|
||||
Не выводи target только из наличия `next.config.*`. Проверь фактические flags в `dev`/`build`. Mode генератора и сборщик контрольной сборки должны совпадать.
|
||||
|
||||
## Подготовка каталога спрайта
|
||||
|
||||
@@ -23,16 +23,23 @@ src/ui/file-manager/svg-sprite/
|
||||
└── svg-sprite.config.ts
|
||||
```
|
||||
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineNextSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineNextSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
- Для обычной CLI-генерации пакет устанавливать не нужно. При локальной установке ради SpriteViewer или программного API объект можно опционально обернуть в `defineNextSpriteConfig(...)` для autocomplete.
|
||||
- Каталог выбирает проект конкретного спрайта и не обязан быть module/feature-каталогом. Каждый config описывает один из потенциально многих спрайтов приложения.
|
||||
- Конфиг называется в единственном числе: `svg-sprite.config.ts`.
|
||||
- Пути считаются от его каталога; `inputFolder` сканируется нерекурсивно.
|
||||
@@ -44,24 +51,12 @@ export default {
|
||||
|
||||
## Генерация
|
||||
|
||||
Для Turbopack:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@app/turbopack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Для Webpack 5:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@app/webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Пример scripts для Turbopack:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode next@app/turbopack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode next@app/turbopack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -69,7 +64,7 @@ npx --yes @gromlab/svg-sprites@latest --mode next@app/webpack src/ui/file-manage
|
||||
}
|
||||
```
|
||||
|
||||
Для Webpack замени только mode целиком на `next@app/webpack`. Не запускай два target последовательно для одного каталога: второй перезапишет generated target первого.
|
||||
Для Webpack замени только mode целиком на `next@app/webpack`. Не запускай два target последовательно для одного каталога: второй перезапишет generated target первого. Для первой генерации запусти `npm run sprite:file-manager`.
|
||||
|
||||
## Server Component
|
||||
|
||||
@@ -95,12 +90,6 @@ export default function Page() {
|
||||
|
||||
Viewer интерактивен и импортируется из client-only entry. Создай отдельную Client Component страницу или дочерний компонент:
|
||||
|
||||
Для Viewer установи пакет локально:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
|
||||
@@ -124,23 +113,15 @@ export default function SpritesPage() {
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
npx tsc --noEmit
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Если менялись target или Next build/deployment pipeline либо диагностируется runtime, затем запусти ровно одну production-сборку, соответствующую target:
|
||||
Если менялись target или Next build/deployment pipeline либо диагностируется runtime, запусти production-сборку проекта, настроенную на выбранный сборщик:
|
||||
|
||||
```bash
|
||||
npx next build --turbopack
|
||||
npm run build
|
||||
```
|
||||
|
||||
или:
|
||||
|
||||
```bash
|
||||
npx next build --webpack
|
||||
```
|
||||
|
||||
Для Next 13-15 Webpack используй `npx next build` без flag.
|
||||
|
||||
После обязательных генерации и typecheck проверь:
|
||||
|
||||
- `manifest.ts` содержит точный target `next@app/turbopack` либо `next@app/webpack`;
|
||||
@@ -157,7 +138,7 @@ npx next build --webpack
|
||||
|
||||
- `Next.js mode requires a router and bundler`: нельзя использовать `--mode next`; укажи полный mode.
|
||||
- Сборка проходит на одном bundler, а runtime asset ломается на другом: перегенерируй тем target, которым реально выполняется build.
|
||||
- В Next 16 выбран Webpack, но build ушёл в Turbopack: используй `next build --webpack` и `next@app/webpack`.
|
||||
- Выбран Webpack, но build ушёл в Turbopack: используй Webpack-команду проекта и `next@app/webpack`.
|
||||
- Viewer вызывает ошибку Server Component: файл с Viewer должен иметь `'use client'`; generated icon component этого не требует.
|
||||
- `React config file not found`: команда получила путь к `app/`, `icons/` или конфигу вместо каталога спрайта.
|
||||
- Две CI jobs генерируют разные target в одном checkout: раздели каталоги или обеспечь один согласованный target на job.
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
|
||||
## Выбор target
|
||||
|
||||
| Сборщик | CLI mode | Минимальная версия Next.js | Условная проверка build |
|
||||
|---|---|---:|---|
|
||||
| Turbopack | `next@pages/turbopack` | 16.2 | `npx next build --turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` | 12.2 | Next 12-15: `npx next build`; Next 16: `npx next build --webpack` |
|
||||
| Сборщик | CLI mode |
|
||||
|---|---|
|
||||
| Turbopack | `next@pages/turbopack` |
|
||||
| Webpack 5 | `next@pages/webpack` |
|
||||
|
||||
Для Next.js 12.2 требуется React 18. Определи установленную версию и реальные flags scripts до выбора mode. Наличие Pages Router не означает автоматически Webpack: в Next 16.2 поддерживается Turbopack.
|
||||
Определи реальные flags scripts до выбора mode. Наличие Pages Router не означает автоматически Webpack: выбирай target по сборщику проекта.
|
||||
|
||||
## Структура и конфиг
|
||||
|
||||
@@ -23,16 +23,24 @@ src/ui/file-manager/svg-sprite/
|
||||
└── svg-sprite.config.ts
|
||||
```
|
||||
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineNextSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineNextSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Для обычной CLI-генерации пакет устанавливать не нужно. При локальной установке ради SpriteViewer или программного API config можно опционально обернуть в `defineNextSpriteConfig(...)` для autocomplete. Каталог с config выбирает проект конкретного спрайта и не обязан быть module/feature-каталогом; каждый config описывает один из потенциально многих спрайтов приложения.
|
||||
Каталог с config выбирает проект конкретного спрайта и не обязан быть module/feature-каталогом; каждый config описывает один из потенциально многих спрайтов приложения.
|
||||
|
||||
Все source paths разрешаются от каталога конфига. `inputFolder` по умолчанию `./icons`, сканирование не рекурсивно. `inputFiles` объединяется с папкой. Один и тот же путь дедуплицируется, но два разных `check.svg` конфликтуют. Явная отсутствующая папка считается ошибкой даже при заполненном `inputFiles`.
|
||||
|
||||
@@ -40,24 +48,12 @@ export default {
|
||||
|
||||
## Команды
|
||||
|
||||
Webpack 5:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@pages/webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Turbopack:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode next@pages/turbopack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Пример lifecycle для Webpack:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode next@pages/webpack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode next@pages/webpack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -65,7 +61,7 @@ npx --yes @gromlab/svg-sprites@latest --mode next@pages/turbopack src/ui/file-ma
|
||||
}
|
||||
```
|
||||
|
||||
Если pre-scripts уже существуют, добавь генерацию в текущую цепочку. Generated imports отсутствуют в Git, поэтому генерация должна предшествовать TypeScript и Next compilation.
|
||||
Если pre-scripts уже существуют, добавь генерацию в текущую цепочку. Generated imports отсутствуют в Git, поэтому генерация должна предшествовать TypeScript и Next compilation. Для Turbopack замени mode целиком на `next@pages/turbopack`. Для первой генерации запусти `npm run sprite:file-manager`.
|
||||
|
||||
## Использование в Pages Router
|
||||
|
||||
@@ -89,12 +85,6 @@ export function getServerSideProps() {
|
||||
|
||||
Pages Router компоненты выполняются и на клиенте, поэтому отдельная директива `'use client'` не нужна:
|
||||
|
||||
Для SpriteViewer установи пакет локально:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
@@ -114,23 +104,15 @@ export default function SpritesPage() {
|
||||
|
||||
```bash
|
||||
npm run sprite:file-manager
|
||||
npx tsc --noEmit
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
Если менялись target или Next build/deployment pipeline либо диагностируется runtime, запусти production build для выбранного bundler:
|
||||
Если менялись target или Next build/deployment pipeline либо диагностируется runtime, запусти production build проекта, настроенный на выбранный сборщик:
|
||||
|
||||
```bash
|
||||
npx next build --turbopack
|
||||
npm run build
|
||||
```
|
||||
|
||||
или для Next 16 Webpack:
|
||||
|
||||
```bash
|
||||
npx next build --webpack
|
||||
```
|
||||
|
||||
В Next 12-15 Webpack запускай `npx next build`.
|
||||
|
||||
После обязательных генерации и typecheck проверь:
|
||||
|
||||
- `manifest.ts` содержит `next@pages/turbopack` либо `next@pages/webpack`;
|
||||
@@ -146,8 +128,7 @@ npx next build --webpack
|
||||
## Типовые ошибки
|
||||
|
||||
- В mode указан `next@app/...`: модуль может сгенерироваться, но manifest и контракт target неверны; используй `next@pages/...`.
|
||||
- В Next 16 command и mode выбирают разные bundler: добавь соответствующий build flag и перегенерируй.
|
||||
- На Next 12.2 используется React 17: обнови React до 18 прежде, чем диагностировать sprite runtime.
|
||||
- Command и mode выбирают разные bundler: используй соответствующую build-команду проекта и перегенерируй.
|
||||
- Viewer manifest не попадает в chunk: путь `import()` должен быть строковым литералом и существовать до Next build.
|
||||
- Иконка есть после full reload, но пропадает при переходе: проверь доступность внешнего asset с `basePath`, `assetPrefix` и production origin.
|
||||
- `Refusing to overwrite a user file`: sprite-каталог содержит неуправляемый файл с зарезервированным именем; перенеси его.
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
## Обязательная установка
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
Программные imports требуют локальной dependency: `npx` их не заменяет. Этот reference всегда относится к latest API пакета.
|
||||
Программные imports требуют локальной development dependency, установленной выше. Этот reference описывает API установленной версии пакета.
|
||||
|
||||
## Когда открывать
|
||||
|
||||
|
||||
@@ -23,18 +23,25 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
## Настройка
|
||||
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
`src/ui/file-manager/svg-sprite/svg-sprite.config.ts`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
- Для обычной CLI-генерации пакет устанавливать не нужно. Если он уже установлен локально ради SpriteViewer или программного API, `defineReactSpriteConfig(...)` можно использовать как необязательный helper для autocomplete.
|
||||
- Каждый такой config описывает один конкретный спрайт; в приложении может быть много независимых config и спрайтов.
|
||||
- Все пути в конфиге разрешаются относительно каталога `svg-sprite.config.ts`.
|
||||
- `inputFolder` по умолчанию равен `./icons`; сканирование папки не рекурсивно и включает файлы с окончанием `.svg`.
|
||||
@@ -46,18 +53,12 @@ export default {
|
||||
|
||||
## Команда и scripts
|
||||
|
||||
Точная команда для примера выше:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Закрепи её в `package.json` и запускай до процессов, которым нужны generated imports:
|
||||
Добавь локальный CLI в `package.json` и запускай до процессов, которым нужны generated imports:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@vite src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -67,6 +68,8 @@ npx --yes @gromlab/svg-sprites@latest --mode react@vite src/ui/file-manager/svg-
|
||||
|
||||
Если в проекте уже есть `predev` или `prebuild`, объедини команды в существующем orchestration вместо перезаписи script.
|
||||
|
||||
Для первой генерации запусти `npm run sprite:file-manager`.
|
||||
|
||||
## Использование
|
||||
|
||||
Импортируй только публичный локальный entry:
|
||||
@@ -118,11 +121,7 @@ import spriteUrl from './svg-sprite/generated/sprite.svg?no-inline'
|
||||
|
||||
## SpriteViewer
|
||||
|
||||
После генерации при необходимости установи пакет и добавь Viewer только на debug-маршрут:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
После генерации добавь Viewer только на debug-маршрут:
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
@@ -23,31 +23,33 @@ src/ui/file-manager/svg-sprite/
|
||||
|
||||
## Конфигурация и генерация
|
||||
|
||||
Установи пакет как development dependency:
|
||||
|
||||
```bash
|
||||
npm install --save-dev @gromlab/svg-sprites
|
||||
```
|
||||
|
||||
```ts
|
||||
export default {
|
||||
import { defineReactSpriteConfig } from '@gromlab/svg-sprites'
|
||||
|
||||
export default defineReactSpriteConfig({
|
||||
name: 'file-manager',
|
||||
description: 'Иконки файлового менеджера',
|
||||
inputFolder: './icons',
|
||||
inputFiles: ['../../../../shared/icons/check.svg'],
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Для обычной CLI-генерации пакет устанавливать не нужно. При локальной установке ради SpriteViewer или программного API config можно опционально обернуть в `defineReactSpriteConfig(...)` для autocomplete. Каждый config описывает один из потенциально многих независимых спрайтов приложения.
|
||||
Каждый config описывает один из потенциально многих независимых спрайтов приложения.
|
||||
|
||||
Пути считаются от `svg-sprite.config.ts`. Папка сканируется только на первом уровне. `inputFolder` и `inputFiles` объединяются; одинаковый путь дедуплицируется, но одинаковые basename у разных файлов вызывают конфликт ID. Неявный `./icons` можно не создавать, если заполнен `inputFiles`; явно заданная отсутствующая папка является ошибкой. `FileManagerIcon` ниже — только пример generated-имени из `name: 'file-manager'`.
|
||||
|
||||
Точная команда:
|
||||
|
||||
```bash
|
||||
npx --yes @gromlab/svg-sprites@latest --mode react@webpack src/ui/file-manager/svg-sprite
|
||||
```
|
||||
|
||||
Рекомендуемые lifecycle hooks:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"sprite:file-manager": "npx --yes @gromlab/svg-sprites@latest --mode react@webpack src/ui/file-manager/svg-sprite",
|
||||
"sprite:file-manager": "svg-sprites --mode react@webpack src/ui/file-manager/svg-sprite",
|
||||
"predev": "npm run sprite:file-manager",
|
||||
"prebuild": "npm run sprite:file-manager",
|
||||
"pretypecheck": "npm run sprite:file-manager"
|
||||
@@ -55,7 +57,7 @@ npx --yes @gromlab/svg-sprites@latest --mode react@webpack src/ui/file-manager/s
|
||||
}
|
||||
```
|
||||
|
||||
Не затирай уже существующие pre-scripts: включи генерацию в их текущую цепочку. React preset всегда выпускает `stack`.
|
||||
Не затирай уже существующие pre-scripts: включи генерацию в их текущую цепочку. Для первой генерации запусти `npm run sprite:file-manager`. React preset всегда выпускает `stack`.
|
||||
|
||||
## Публичный компонент
|
||||
|
||||
@@ -105,12 +107,6 @@ Webpack 5 распознаёт его как Asset Module и заменяет н
|
||||
|
||||
Webpack не предоставляет `import.meta.glob`. Передай статические lazy imports со строковыми литералами:
|
||||
|
||||
Для SpriteViewer пакет должен быть установлен локально:
|
||||
|
||||
```bash
|
||||
npm install @gromlab/svg-sprites@latest
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { SpriteViewer } from '@gromlab/svg-sprites/react'
|
||||
|
||||
|
||||
Reference in New Issue
Block a user