A Vite plugin which generates .tsx and .astro components from .svg files and directories.
Running the Astro project in this repo offers a minimal setup of the working plugin.
At a minimum we need an outputPath to render our components and types to, and at least one inputPath to grab .svgs from.
A basic Astro example may look like this:
// astro.config.mjs
export default defineConfig({
vite: {
plugins: [
svgToComponent({
inputPaths: [
'/public/icons',
'/public/logos',
],
outputPath: '/src/components/Icon',
})
]
},
});This plugin assumes the existence of a /src/components/ directory and uses a custom path in tsconfig.json.
In the future this assumption could be improved to be more versatile, but for now we just need to add @components to our paths.
// tsconfig.json
{
"compilerOptions": {
"paths": {
"@components/*": [
"src/components/*"
]
}
}
}type ComponentType = 'astro'|'tsx';
interface PluginConfig {
inputPaths: string[];
outputPath: string;
include?: ComponentType[];
exclude?: ComponentType[];
}- Path(s) which plugin uses to find
.svgsto convert.
- Path where output
<Icon />component(s) will be created
<Icon />component file formats to not generate.
<Icon />component file formats to definitely generate.
Add .svgs to your inputPaths directories and components will be automatically generated when the plugin runs.
In an .astro file:
---
import Icon from '@components/Icon/Icon.astro';
---
<Icon icon="astro" />In a .tsx file:
import { Icon } from '@components/Icon/Icon';
export const ReactComponent = () => (
<Icon icon="react" />
);We can also use the .tsx <Icon /> component in an .astro file if we wish:
---
import { Icon } from '@components/Icon/Icon';
---
<Icon icon="react" />We could also be arbitrarily confusing and include them both in an .astro file: ¯\_(ツ)_/¯
---
import IconA from '@components/Icon/Icon.astro';
import { Icon as IconT } from '@components/Icon/Icon';
---
<IconA icon="astro" />
<IconT icon="react" />interface ComponentProps {
icon: Icons;
color?: string;
size?: number;
id?: string;
class?: string;
}- An icon name from the
Iconsmodel generated from.svgfile names found ininputPaths
- A valid color such as hex, rgb, hsla or css variable.
- When not defined, component will use
svg'sdefault colors, includingcurrentColor. - When defined, component will use
svgas a cssmask-imageand apply thecolorto itsbackground-color
- When not defined, component will use
- The icon width and height in pixels.
- Defaults to
16
- Add a referenceable
idto<Icon />component.
- Add a referenceable css
classto<Icon />component.- If using
.tsxcomponent, this param will instead be calledclassName
- If using
Types for <Icon />'s icon param are automatically generated from .svg file names included in inputPaths.
Given an asset directory structure which looks like this:
An Icons model is generated:
And we can expect our component icon types to look like this:




