Managing SVG images in Vue.js applications

Michał Męciński
codeburst
Published in
6 min readOct 7, 2019

--

It’s hard to imagine a modern web application without SVG graphics in the form of icons, logos and other elements of the user interface. A few years ago the typical way of managing SVG images was to use special web fonts which served as collections of icons, for example glyphicons. But these fonts usually contain a lot of icons that you don’t need. Today, the best and most efficient approach is to simply insert SVG images inline into the HTML markup.

When you use a front-end framework like Vue.js, it’s important to realize that a piece of SVG is not any different than a piece of HTML markup. And since SVG images are isolated and reusable, they are no different than regular Vue components.

You can easily convert an SVG image to a single-file Vue component like this:

<template>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<path d="..."/>
</svg>
<template>

Doing this manually for dozens of images isn’t very practical, but fortunately webpack can do this for us. There are a few available solutions, for example:

  • vue-svg-loader, which makes it possible to import .svg files directly as if they were Vue components;
  • vue-template-loader, which is intended to convert static .html files to Vue component templates, but is also works great with .svg files;

Personally I use vue-template-loader, because it’s more flexible.

Configuring webpack

First, we need to install the necessary modules:

$ npm install --save-dev vue-template-loader svgo-loader svgo

In a typical web application we will use both inline SVG images and external SVG images loaded using the <img> tag. I use the following approach:

  • Since inline SVG images are basically Vue components, I place them in the src/components/svg folder of the application.
  • All external SVG images are placed together with PNG, JPEG and other files in the src/images folder.

I will talk about why this separation is important later. First, let’s take a look at the following fragment of webpack configuration that tells it how to handle SVG files:

--

--