Vite svgr component plugin
Vite zero-config customizable plugin to import SVG and transform it to a React component in a simple way.
🚀 Features
- 👌 Zero-config: built-in default configs for common use cases
- ✅ Easy import: Not aditional
?component
string needed - ⚒️ Configurable: full ability to customize the behavior of the plugin
- ⚛️ Transformed with SVGR: svgr library based to transform the svg to a React Component
- ⚡ Optimized SVG: Optimized with SVGO plugin
- 🔑 Fully typed: written in Typescript and extends SVGR options with types
📦 Install
npm i vite-plugin-svgr-component -D
yarn add vite-plugin-svgr-component -D
💻 Usage
Add svgrComponent
plugin to vite.config.js / vite.config.ts
and use it:
By default it will transform all the *.svg
files imported to a React component
import { svgrComponent } from 'vite-plugin-svgr-component';
export default {
plugins: [
svgrComponent()
]
}
import CustomIcon from 'custom-icon.svg';
const Component = (props) => (
<div>
<CustomIcon />
{/* You can add a title by default */}
<CustomIcon title="custom svg title" />
{/* Accesibility (A11y) title props linked to titleId prop */}
<CustomIcon title="custom svg title" titleId="custom-icon"/>
</div>
)
🛠️ Config
Change import pattern to be transformed
As it uses micromatch under the hood, you can set a string pattern to transform specific svg file imports
export default {
plugins: [
svgrComponent({ importStringPattern: '*-embedded.svg' })
]
}
Change SVGR options
As it uses svgr under the hood, you can set all the available options to generate the react component. Here you have an example:
export default {
plugins: [
svgrComponent({
svgrOptions: {
ref: true,
icon: true,
}
})
]
}
Use with Typescript
If you use the plugin in a Typescript project you will need the reference to the type definitions
to allow to use "title" and "titleId" in your SVGComponent
🔑 Full config
Check out the type declaration src/index.ts with all the related types
Created with Typescript! ⚡ and latin music 🎺🎵