How to automate svg sprite building to reduce http requests
- Step 1Install vite-plugin-svg-icons — npm install vite-plugin-svg-icons -D. Add to vite.config.ts: createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), 'src/icons')], symbolId: 'icon-[name]' }).
- Step 2Configure the icon component — Create a reusable Icon component that renders svg > use href=#icon-{name}. Import createSvgIconsPlugin's virtual module in your main.ts to register all icons at startup.
- Step 3Generate TypeScript types — Run the type-generation script: node scripts/generate-icon-types.js. It reads the icons folder and outputs an IconName type union — autocomplete and compile-time checking for all icon names.
Frequently asked questions
Does the Vite plugin support HMR when icons change?+
Yes. vite-plugin-svg-icons watches the icon directory and hot-reloads the virtual sprite module when any SVG file changes. No full page reload needed during development — the icon updates instantly.
How do I add a content hash to the sprite file for cache-busting?+
Vite handles this automatically when you set build.rollupOptions.output.assetFileNames with a [hash] pattern. The sprite file gets a unique hash in its filename on each build, and the virtual module reference is updated automatically.
Can I split icons into multiple sprites for code splitting?+
Yes. Create multiple icon directories and instantiate the plugin multiple times with different symbolId prefixes. Lazy-load secondary sprites on demand using dynamic import of the sprite's virtual module.
How do I use SVG sprites in a Next.js App Router project?+
Place the sprite in the public/ folder and reference it with an absolute URL: /sprite.svg#icon-name. For inline sprites (needed for CSS fill styling), fetch the sprite server-side in a layout component and dangerouslySetInnerHTML it into a hidden div at the top of the body.
Privacy first
Every JAD SVG tool runs entirely in your browser using the DOM API and Canvas. Your SVG files never leave your device — verified by zero outbound network requests during processing.