svg-sprite-pack
v1.0.2
Published
Pure JavaScript SVG sprite generator
Downloads
9
Readme
svg-sprite-pack
A tool that combines multiple SVG files into a single sprite sheet. It generates SVG sprites with <symbol> elements that can be referenced using <use> tags.
Why use SVG sprites?
SVG sprites with <use> allow CSS styling and adapting icons to light/dark themes. Bundling icons into sprites reduces request overhead even with HTTP/2. Cross-origin <use> references are blocked, so CDN hosting won't work for the sprite file.
Installation
npx svg-sprite-pack <directory>How it works
The tool looks for directories named sprite in your project and transforms all the SVG files inside into a single optimized sprite sheet. Each icon becomes a <symbol> with an ID based on its filename. Style attributes like fill and stroke are stripped out so you can control everything with CSS. The final sprite is saved next to your component with a -sprite.svg suffix.
Quick start
Create a sprite directory next to your component and drop your SVG icons in there:
src/components/AppSwitch/
├── sprite/
│ ├── play.svg
│ └── pause.svg
├── AppSwitch.tsx
└── AppSwitch.module.cssRun the tool:
npx svg-sprite-pack src/componentsYou'll get AppSwitch-sprite.svg next to your component. Use it in your code:
import sprite from './AppSwitch-sprite.svg?url';
<svg width={24} height={24}>
<use xlinkHref={`${sprite}#play`} />
</svg>The ?url import syntax depends on your bundler — adjust as needed. The important part is getting a URL to your sprite file.
Features
The tool recursively searches for directories named sprite and generates optimized sprite files. It automatically converts filenames into slugified IDs (my-icon.svg becomes #my-icon) and applies SVGO optimization to minimize file size. No build configuration or native dependencies required — just Node.js 18 or later.
