vite-plugin-svg-icons

repository·main·Indexed 21 days ago

https://github.com/vbenjs/vite-plugin-svg-icons

A Vite plugin that automatically generates an SVG sprite map from a directory of SVG files for high-performance icon usage via the <use> element. It supports SVGO compression, customizable symbol ID templates, and flexible DOM injection positions. The plugin provides virtual modules for registration (virtual:svg-icons-register) and retrieving registered icon names (virtual:svg-icons-names).

Tokens
3.4K
Snippets
15
Records
20
Agent score
73%

What's inside vite-plugin-svg-icons

  1. Understand the symbolId format

    main

    The symbolId determines how you reference icons in your code. The default format is icon-[dir]-[name].

    • [name]: The filename of the SVG.
    • [dir]: The directory structure within iconDirs used to prevent name collisions.

    Example mapping: If your directory structure is:

    • src/icons/icon1.svg $\rightarrow$ icon-icon1
    • src/icons/dir/icon1.svg $\rightarrow$ icon-dir-icon1
    • src/icons/dir/dir2/icon1.svg $\rightarrow$ icon-dir-dir2-icon1
  2. Install vite-plugin-svg-icons

    main

    Install the plugin as a development dependency using your preferred package manager. Requires Node.js >=12.0.0 and Vite >=2.0.0.

    yarn add vite-plugin-svg-icons -D
    # or
    npm i vite-plugin-svg-icons -D
    # or
    pnpm install vite-plugin-svg-icons -D
  3. Register the SVG icons in your entry point

    main

    After configuring the plugin, you must import the virtual module virtual:svg-icons-register in your main entry file (e.g., src/main.ts) to ensure the SVG sprite map is generated and available.

    import 'virtual:svg-icons-register'
  4. Configure createSvgIconsPlugin in vite.config.ts

    main

    To use the plugin, import createSvgIconsPlugin and add it to your Vite configuration. You must specify iconDirs (the directories containing your SVG files) and can customize the symbolId format, injection position, and the DOM ID used for the sprite container.

    import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    import path from 'path'
    
    export default () => {
      return {
        plugins: [
          createSvgIconsPlugin({
            // Specify the icon folders to cache
            iconDirs: [path.resolve(process.cwd(), 'src/icons')],
            // Specify the symbolId format
            symbolId: 'icon-[dir]-[name]',
    
            /**
             * Custom insertion position
             * @default: 'body-last'
             */
            inject?: 'body-last' | 'body-first'
    
            /**
             * custom dom id
             * @default: '__svg__icons__dom__'
             */
            customDomId: '__svg__icons__dom__',
          }),
        ],
      }
    }
  5. Configure symbol ID templates

    main

    The symbolId option allows you to define how the generated SVG <symbol> IDs are named. This is crucial for referencing icons in your markup.

    Placeholders

    • [name]: The filename of the SVG (without extension).
    • [dir]: The directory path relative to the iconDirs root, joined by hyphens.

    Examples

    • If symbolId: 'icon-[dir]-[name]' and the file is src/assets/icons/user/profile.svg:
      • Resulting ID: icon-user-profile
    • If symbolId: '[name]' and the file is src/assets/icons/home.svg:
      • Resulting ID: home

    Note: You must include [name] in your template string.

  6. Use SVG icons in React components

    main

    In React, create a component that accepts name, prefix, and color props, and renders an <svg> element using the <use> tag with the formatted symbolId.

    export default function SvgIcon({
      name,
      prefix = 'icon',
      color = '#333',
      ...props
    }) {
      const symbolId = `#${prefix}-${name}`
    
      return (
        <svg {...props} aria-hidden="true">
          <use href={symbolId} fill={color} />
        </svg>
      )
    }
  7. Use SVG icons in Vue components

    main

    To use icons in Vue, create a component that uses the <use> element to reference the generated symbolId.

    Example SvgIcon.vue:

    <template>
      <svg aria-hidden="true">
        <use :href="symbolId" :fill="color" />
      </svg>
    </template>
    
    <script>
    import { defineComponent, computed } from 'vue'
    
    export default defineComponent({
      name: 'SvgIcon',
      props: {
        prefix: { type: String, default: 'icon' },
        name: { type: String, required: true },
        color: { type: String, default: '#333' },
      },
      setup(props) {
        const symbolId = computed(() => `#${props.prefix}-${props.name}`)
        return { symbolId }
      },
    })
    </script>
    <template>
      <div>
        <SvgIcon name="icon1"></SvgIcon>
        <SvgIcon name="dir-icon1"></SvgIcon>
      </div>
    </template>
    
    <script>
    import { defineComponent } from 'vue'
    import SvgIcon from './components/SvgIcon.vue'
    
    export default defineComponent({
      name: 'App',
      components: { SvgIcon },
    })
    </script>
  8. Configure vite-plugin-svg-icons options

    main

    When initializing the vite-plugin-svg-icons plugin in your vite.config.ts, you can provide a configuration object of type ViteSvgIconsPlugin. This allows you to define where your icons are located, how they are compressed, and how the SVG sprite is injected into the DOM.

    import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
    
    export default defineConfig({
      plugins: [
        createSvgIconsPlugin({
          // Configuration options go here
        }),
      ],
    });