svg-sprite-gen
v1.0.1
Published
Given a folder of SVGs, it optimizes, inlines, and bundles them into a single SVG-sprite (with <symbol> tags), plus a React hook for easy lookup.
Maintainers
Readme
svg-sprite-gen
A CLI tool to generate an optimized SVG sprite and React hook from a folder of SVG icons.
🚀 Features
- SVG Optimization: Uses SVGO to compress and clean up individual SVG files.
- Sprite Generation: Bundles all optimized SVGs into a single
<svg>sprite sheet with<symbol>entries. - React Integration: Produces a ready-to-use React hook (e.g.,
useSvgSprite) to inject the sprite into the DOM. - Configurable: Customize input directory, output filenames, and hook name via flags.
- Zero Runtime Dependencies: Pure Node.js implementation, no browser-side library dependencies.
💿 Installation
npm install -g svg-sprite-genRequires Node.js v16+.
⚙️ CLI Usage
svg-sprite-gen -i <input-dir> [options]Options
| Flag | Description | Default |
| --------------- | -------------------------------------------------- | -------------- |
| -i, --input | Path to source directory containing .svg files | (required) |
| -o, --output | Output sprite filename (relative or absolute path) | sprite.svg |
| --hook <name> | Name of generated React hook | useSvgSprite |
| -V, --version | Show CLI version | — |
| -h, --help | Display help information | — |
Examples
Generate a sprite from your icons/ folder:
svg-sprite-gen -i ./iconsCreates sprite.svg and sprite.hook.ts in the current directory.
Specify a custom output path and hook name:
svg-sprite-gen -i ./assets/svg -o public/icons.svg --hook useIconSprite🛠️ How It Works
- Collect SVGs: Uses
fast-globto find all.svgfiles in the input directory. - Optimize: Runs each SVG through SVGO for minification.
- Wrap: Strips outer
<svg>tags and wraps content in<symbol id="<filename>">. - Combine: Concatenates all
<symbol>s into one<svg>sprite withdisplay: none. - Hook: Generates a React hook that injects the sprite into
<body>on mount.
🌀 Development
Clone the repo and install dependencies:
git clone https://github.com/your-username/svg-sprite-gen.git
cd svg-sprite-gen
npm installBuild and link locally:
npm run build
npm linkRun the CLI:
svg-sprite-gen --help🤝 Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a new branch:
git checkout -b feature/your-feature - Make your changes and commit:
git commit -m "feat: describe your feature" - Push to your branch:
git push origin feature/your-feature - Open a Pull Request
📜 License
This project is licensed under the MIT License. See the LICENSE file for details.
