Import SVG to Vite + Vue projects

Vite SVG loader guide for better-importing SVGs

Oleksandr Shevchuk
2 min readOct 10, 2023

Vite is a modern and powerful tool for creating web applications and has quickly gained popularity. However, there are some differences you need to know, especially if you switch from Webpack or another bundler. For instance: Vite doesn’t support the CommonJS require , which is widely used in Webpack. This guide has provided a comprehensive overview of the process, from installation and configuration to best practices for importing SVGs efficiently.

Vite SVG loader

Vite supports importing static SVG by default. But if you need more install the vite-svg-loader package:

npm install vite-svg-loader --save-dev

Configure vite.config.js :

import svgLoader from 'vite-svg-loader'

export default defineConfig({
plugins: [vue(), svgLoader()]
})

The Vite SVG loader not only simplifies the importing of SVG but also offers the flexibility to customize the behavior and optimize your project’s assets. It provides a few different ways of importing.

URL

It’s the simplest way, but the benefit is that your SVG wouldn’t be included in your javascript bundle. If you need to import a weighty static image use a ?url suffix. The image will be imported as a URL:

import SvgImage from './src/assets/my-image.svg?url'
// '/assets/my-image.1925b929.svg'
<img :src="SvgImage" alt="My image" />

Inline SVG

Another way to import SVG. In this case, the import returns a string with inline SVG. The benefit is obvious, you have much wider styling options than the import as URL. Add a ?raw suffix to select this import type:

import SvgImage from './src/assets/my-image.svg?raw'
// '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">...'
<div class="svg-image" v-html="SvgImage"></div>
.svg-image:hover {
color: green
}

Vue.js component

Best way to import dynamic images like icons. Use the ?component suffix and the SVG will be explicitly imported as a Vue component with all its advantages:

import SvgImage from './src/assets/my-image.svg?component'
<SvgImage width="20" />

Conclusion

Vite SVG loader provides a few ways to import SVGs to a Vue.js project. Each of them has its pros and cons, and now you can choose the most suitable. By following the steps outlined in this guide, you can enhance your web development workflow, reduce page load times, and ensure your projects remain lightweight and performant.

🙏 Hope that you just read an interesting and helpful story.

👏 If you like it just send a clap, I’ll be very excited to see your reaction!

👆Follow me to be the first who will see my new articles.

Thanks and BR Oleksandr

--

--