Load .svg files from a folder with auto-generated TypeScript types based on their file names.
introduction.mp4
This plugin was inspired by SvelteKit’s generated types. I wanted a way to load an entire folder of SVG files with autocompletion for file names, making icon imports more type-safe and developer-friendly.
When you add this plugin:
- File scanning – It scans all
.svgfiles inside the folder you specify (svgFolderPath). - Virtual module generation – At build time, it creates a virtual module (
virtual:svg-ts) containing:- An object mapping each file name → SVG file import resolve results (via
?rawor?reactquery). - A TypeScript type (
SvgName) with all valid SVG file names.
- An object mapping each file name → SVG file import resolve results (via
- Types output – It writes the
.d.tsfile into.svg-ts/virtual-module.d.ts. This file is used by your editor to provide autocompletion and type-checking when referencing icons.
Example: If you have arrow-left.svg and arrow-right.svg in your folder, the generated type file will be:
declare module "virtual:svg-ts" {
export type SvgName =
| 'arrow-left'
| 'arrow-right'
const svgs: Record<SvgName, string>;
export default svgs;
}And you can safely reference them in your code with autocomplete.
npm install --save-dev vite-plugin-svg-tsThe plugin generates types in the .svg-ts folder at the project root.
It’s recommended to add this folder to .gitignore and formatter config file:
.svg-ts
- Add support for more frameworks
- Allow customizing the output path for generated types
- Explore ways to optimize SVG files automatically