SVG sprite plugin for Vite
npm i vite-plugin-svg-sprite -D
Add the plugin to your vite.config.js
:
import createSvgSpritePlugin from 'vite-plugin-svg-sprite';
const config = {
plugins: [
createSvgSpritePlugin({
symbolId: 'icon-[name]-[hash]',
}),
],
}
Then use it like that in your app code:
import appIconId from './path/to/icons/app.svg';
// react or vue component, as you want
export default function App() {
return (
<svg>
<use
xlinkHref={`#${appIconId}`}
/>
</svg>
);
}
You can also access the width
/height
attributes of the SVG with the size
export:
import appIconId, { size } from './path/to/icons/app.svg';
// react or vue component, as you want
export default function App() {
return (
<svg {...size}>
<use
xlinkHref={`#${appIconId}`}
/>
</svg>
);
}
If you're using TypeScript, add the following line to your vite-env.d.ts
:
/// <reference types="vite/client" />
+ /// <reference types="vite-plugin-svg-sprite/client" />
const plugin = createSvgSpritePlugin(options);
For generating the id
attribute of <symbol>
element. Defaults to [name]
Match files that will be transformed. Defaults to '**.svg'
. See micromatch for the syntax document.
Enable SVGO for optimizing SVG. Defaults to true
.