In this episode, we take a look at the best ways to work with SVG icons in a Vue project that's set up with Vite. SVGs are something pretty much every project uses, so it's super handy to know a maintainable way to work with them.
First, we see the very most basic method: just copy-pasting the SVG markup right into your Vue file. It works, but quickly gets messy and hard to maintain — so that's not ideal for projects with lots of icons.
To improve things, we install the vite-svg-loader
package. This lets us import SVG files directly into Vue components like they're regular Vue components. Much more convenient! We go through adding the loader to vite.config.js
and using it to import and display an SVG file as a component.
But what if our project has a ton of icons? Importing each one manually gets messy, so the next step is to build a custom SVG component. We make an <Svg />
component that takes just a name
prop. Under the hood, it dynamically imports the right SVG file based on the name you give it, so you only have to add one import in your script! We also make sure you can still use classes and styles with your icons.
By the end of the episode, you’ll have a neat and scalable way to work with SVG icons in your Vue + Vite projects. Just add your new icons to the folder, and use <Svg name="icon-name" />
anywhere in your app. Easy!