Vite

Building an SVG icon sprite with Vite and Vue

Combine a local SVG icon set into a DOM sprite, render symbols through a Vue component, and verify the resulting asset and request counts.

Building an SVG icon sprite with Vite and Vue

A dashboard can use dozens of SVG icons without needing dozens of icon requests. I group the files into a symbol sprite at build time and render each symbol through a small Vue component.

The example uses Vite, Vue 3, TypeScript, and vite-plugin-svg-icons.

Choose how the icon reaches the page

Independent <img> assets load through the normal image cache and keep vector data out of the JavaScript. The page may request many files, and CSS on the host element cannot directly set the fill of an external SVG’s internal paths. Converting icons to components gives every caller direct control over attributes. The generated component and path data can add substantial JavaScript if many icons are eagerly imported.

A symbol sprite collects shared shapes under <symbol> elements. Each icon instance uses <use> to reference one symbol. This fits a view that reuses a known set of icons across tables, navigation, and status badges. An independently loaded image or a lazily imported component can be a better fit for large illustrations and rarely visited feature areas.

MethodPer-icon requestStyling implications
External imageUsually one per distinct uncached fileHost CSS does not control the image’s individual paths
SVG componentDelivered with the JavaScript that imports itDirect access to props, fill, and other attributes
DOM spriteThe shared registration brings the symbols in togetherSymbols can follow currentColor when the shapes permit it

Build the sprite from the icon directory

I use vite-plugin-svg-icons to avoid manually editing a large sprite whenever a designer replaces a source SVG. The plugin scans the icon directories, applies SVGO, and assigns a symbol ID to each optimized shape. The runtime registration imports the resulting collection.

flowchart LR
    subgraph Filesystem["1. Local icon files"]
        SVG1["src/assets/icons/user.svg"]
        SVG2["src/assets/icons/dashboard.svg"]
        SVG3["src/assets/icons/settings.svg"]
    end
    subgraph VitePlugin["2. vite-plugin-svg-icons pipeline"]
        Scan["Scan and watch directories"]
        SVGO["Optimize the SVGs with SVGO"]
        Symbol["Convert shapes to symbols"]
        Sheet["Generate one sprite"]
        Scan --> SVGO --> Symbol --> Sheet
    end
    subgraph RuntimeDOM["3. Browser registration"]
        Virtual["import 'virtual:svg-icons-register'"]
        DOMInsert["Mount the hidden SVG sprite"]
        UseTag["Render instances with use"]
        Virtual --> DOMInsert --> UseTag
    end
    SVG2 --> Scan
    Sheet --> Virtual

Install the plugin as a development dependency.

1
pnpm add -D vite-plugin-svg-icons

The config uses absolute source paths and a symbol ID template of icon-[dir]-[name]. A directory name can keep two identically named files from colliding. Add only folders whose icons belong in this shared sprite.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// vite.config.ts
import { defineConfig } from 'vite';
import path from 'path';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      // Absolute source directories for icon files
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      // Generated symbol ID pattern (default: icon-[dir]-[name])
      symbolId: 'icon-[dir]-[name]',
      // Set SVGO optimization options
      svgoOptions: {
        plugins: [
          {
            name: 'removeAttrs',
            params: {
              // Remove fixed fills so monochrome icons can inherit color
              attrs: '(stroke|fill)'
            }
          }
        ]
      },
      // ID of the SVG container added to the document
      customDomId: '__svg__icons__dom__'
    })
  ]
});

Remove hard-coded fills only for a collection whose icons are intended to inherit color. A multicolor icon, an intentional fill="none", or a meaningful stroke can change appearance when a broad attribute removal rule is applied. Keep original colors or split the source directories when needed.

Register the virtual module and render a symbol

Import virtual:svg-icons-register in the application entry. The plugin resolves that identifier to generated code. In the browser, the module inserts the hidden sprite into document.body.

1
2
3
4
5
6
7
8
// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';

// Register the SVG sprite in document.body at runtime
import 'virtual:svg-icons-register';

createApp(App).mount('#app');

The Vue component turns the icon name into the matching fragment reference, applies size and color, and uses the sprite without issuing its own image request. The provided component is decorative. Use an accessible label on the surrounding control when the icon conveys the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!-- src/components/SvgIcon.vue -->
<template>
  <svg :class="['svg-icon', className]" :style="iconStyle" aria-hidden="true">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from 'vue';

interface Props {
  // Icon name matching the generated symbol ID
  name: string;
  prefix?: string;
  color?: string;
  size?: number | string;
  className?: string;
}

const props = withDefaults(defineProps<Props>(), {
  prefix: 'icon',
  color: 'currentColor',
  size: 20,
  className: ''
});

const symbolId = computed(() => `#${props.prefix}-${props.name}`);

const iconStyle = computed(() => {
  const s = typeof props.size === 'number' ? `${props.size}px` : props.size;
  return {
    width: s,
    height: s,
    verticalAlign: '-0.15em',
    overflow: 'hidden'
  };
});
</script>

<style scoped>
.svg-icon {
  display: inline-block;
  outline: none;
}
</style>

The same structure works in JSX. Use names that include the directory segment when it is part of the plugin’s symbol ID. An incorrect name points to a fragment that does not exist, which often looks like a missing icon with no obvious JavaScript error.

Give icon names to TypeScript

A union makes allowed icon names explicit. Connect it to the component by importing IconName and changing Props.name from string to that union. Maintain the list when adding icons, or generate it from the source if the collection changes often.

1
2
3
4
5
6
7
// src/types/icon.d.ts
export type IconName = 
  | 'dashboard'
  | 'user-avatar'
  | 'settings'
  | 'notification'
  | 'arrow-right';

Inspect the build and the rendered DOM

Run pnpm vite build and check the emitted files. The sample contains 38 input SVGs. SVGO reduced the measured icon data from 48.6 KB to 14.2 KB, about 70.8 percent. The compiled sprite replaced separate output files for those icons, and icon instances no longer needed one HTTP request per shape.

Terminal output summarizing the Vite SVG sprite production build Figure 1. The measured build combines 38 inputs and emits the optimized sprite data.

In development, inspect the live DOM after the registration module runs. The __svg__icons__dom__ container holds the <symbol> definitions. A component refers to one with a fragment such as #icon-dashboard. A raw HTML response can help trace the module entry, but the Elements panel shows the DOM after the module executes.

Vite development inspection showing registered symbols and the SvgIcon fragment reference Figure 2. The hidden container holds the symbols, and an icon instance refers to one by ID.

Check both a visual sample and the Network panel when changing the collection. The sprite saves per-icon fetches, but its registration still ships data for the included set. I also add or edit a temporary icon in development to see how the installed plugin version refreshes the sprite.

Plugin documentation

This post is licensed under CC BY 4.0 by the author.