Vite Plugin SVG Icons

raw JSON →
2.0.1 verified Mon Apr 27 auth: no javascript

Vite plugin for fast creating SVG sprites. Generates an SVG sprite map from a directory of SVG files, supporting HMR, icon selection via DOM injection, and optional SVGO optimization. Current stable version 2.0.1, released under the MIT license. It is a maintained, Vite-specific alternative to svg-sprite-loader or webpack-based solutions, offering tight integration with Vite's dev server and build pipeline since v2.0.0.

error Cannot find module 'vite-plugin-svg-icons'
cause Package not installed or incorrect import path.
fix
Run 'npm install vite-plugin-svg-icons' and ensure the import statement is correct: 'import { vitePluginSvgIcons } from 'vite-plugin-svg-icons''.
error Error: The plugin 'vitePluginSvgIcons' requires Vite >=2.0.0
cause The installed Vite version is lower than 2.0.0.
fix
Upgrade Vite: 'npm install vite@latest'.
error Failed to resolve import 'virtual:svg-icons-register'
cause The virtual module is not registered because the plugin is not properly configured or loaded.
fix
Ensure the plugin is added to the plugins array in vite.config.ts and that the import statement is at the top of your entry file.
breaking Plugin options have changed between v1.x and v2.x. The option 'iconDirs' replaced 'dirs', and 'symbolId' replaced 'symbol_id'.
fix Update your Vite config to use the new option names: iconDirs, symbolId, etc.
deprecated Support for Vite <2.0.0 has been dropped in v2.0.0.
fix Upgrade Vite to version 2.0.0 or later.
gotcha Importing 'virtual:svg-icons-register' is required for the plugin to inject SVG symbols into the DOM. Forgetting this import results in no icons displayed.
fix Add 'import 'virtual:svg-icons-register'' in your application's entry file (e.g., main.js/ts).
gotcha The plugin does not support CommonJS require() due to being ESM-only.
fix Use ES import syntax; ensure your project is configured for ESM.
npm install vite-plugin-svg-icons
yarn add vite-plugin-svg-icons
pnpm add vite-plugin-svg-icons

Sets up the plugin to load SVG files from 'src/icons', configure symbol ID pattern, and enable SVGO optimization.

// vite.config.ts
import { defineConfig } from 'vite';
import { vitePluginSvgIcons } from 'vite-plugin-svg-icons';
import path from 'path';

export default defineConfig({
  plugins: [
    vitePluginSvgIcons({
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      symbolId: 'icon-[dir]-[name]',
      svgoOptions: true,
    }),
  ],
});

// In your application (e.g., main.ts)
import 'virtual:svg-icons-register';

// Using the icon in HTML
// <svg aria-hidden="true">
//   <use xlink:href="#icon-home" />
// </svg>