Blog
Published on

Inline SVG components with Vue 3 & Vite

Authors

Vue SVG Inline Plugin is a plugin for Vue 3 that replaces SVG images with actual SVG contents. I use that in my applications so that I can control some of the SVG's behavior, mainly the size & color.

Basically it replaces <img src="./assets/icons/icon.svg" /> with the content of icon.svg (<svg viewBox="...).

It's a great combination with Tailwind CSS classes so that you can do <img src="./assets/icons/icon.svg" class="h-10 w-10 text-blue-500" />.

Install the plugin with yarn :

$ yarn add vue-svg-inline-plugin

And use it in your main.js file :

import { createApp } from 'vue'
import App from '/@/App.vue'

import VueSvgInlinePlugin from 'vue-svg-inline-plugin'

const app = createApp(App)

app.use(VueSvgInlinePlugin)

app.mount('#app')

Going further

I particularly like the Heroicons set for my apps, I downloaded the outlined & solid styles and put them in my src/assets/icons folders (one folder named outline and the other named solid).

To make my life easier I created an Icon component that I'll use throughout my application.

<template>
  <img
    v-svg-inline
    :src="`/@/assets/icons/${style}/${icon}.svg`"
    class="svg-icon"
  />
</template>
<script>
export default {
  props: {
    icon: {
      type: String,
      required: true,
    },
    outline: {
      type: Boolean,
      default: false,
    },
  },

  computed: {
    style () {
      return this.outline ? 'outline' : 'solid'
    },
  },
}
</script>
<style>
.svg-icon {
  height: 1em;
  width: 1em;
}
</style>

I register it globally in my main.js file to make it available everywhere in the app.

import Icon from '/@/components/base/icon.vue'

// ...

app.component('Icon', Icon)

// ...

And now I can use it like this from anywhere in my app:

<Icon
  icon="bell"
  class="text-xl text-green-500"
/>