vite-plugin-svg-sfc

Convert SVGs to Vue single file component(SFC), support <style> tag

Usage no npm install needed!

<script type="module">
  import vitePluginSvgSfc from 'https://cdn.skypack.dev/vite-plugin-svg-sfc';
</script>

README

vite-plugin-svg-sfc

Npm Version Test codecov

Vite plugin to convert SVGs to Vue single file components(SFC).

🚀 Features

  • Extract <style> tags from SVG to scoped SFC style block.
  • Hot Module Replacement support.
  • Minification with SVGO.

Usage

Install:

npm i -D vite-plugin-svg-sfc

Then add the plugin to your vite.config.js:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import svgSfc from "vite-plugin-svg-sfc";

// If in commonjs module
// const { default: svgSfc } = require("vite-plugin-svg-sfc");


export default defineConfig({
    plugins: [svgSfc(), vue()],
});

SVG files can be imported as Vue component using the ?sfc query:

<template>
    <MyIconComponent/>
    <img :src="myIconUrl" alt="icon">
    <pre>{{ myIconXml }}</pre>
</template>

<script setup>
import MyIconComponent from "../assets/my-icon.svg?sfc";

// vite-plugin-svg-sfc does not affect Vite default asset handling.
import myIconUrl from "../assets/my-icon.svg";
import myIconXml from "../assets/my-icon.svg?raw";
</script>

If you are using TypeScript, vite-plugin-svg-sfc/client can be added to d.ts declaration file.

/// <reference types="vite-plugin-svg-sfc/client" />

Options

extractStyles

Type: boolean

Default: true

When set to true, extract all style elements in the svg and put their content into a scoped SFC style block. This feature is not available when svgo option is false.

Vue template compiler will throw error when the template contains <style>, so we need to move them to top level.

You may notice that SVGO has a inlineStyles plugin that avoid <style> in the SVG by move styles onto the style attribute, but some css features (e.g. media query) can not be inlined.

minify

Type: boolean

Default: true on production mode and false otherwise.

Perform minification for SVG.

responsive

Type: boolean

Default: true

When set to true, some attributes on will be replaced with reactive value:

  • set width & height to "1em".
  • set fill and stroke to "currentColor" if it's not transparent。

svgo

Type: OptimizeOptions | false

Default: {}

Specify the SVGO config to use, set to false to disable processing SVG data.

If svgo.plugins is specified, the extractStyles, minify, and responsiveoptions are ignored, you can enable them manually by add the corresponding plugin :

import svgSfc, { responsivePlugin, extractCSSPlugin } from "vite-plugin-svg-sfc";

svgSfc({
    svgo: {     
        plugins: [     
            responsivePlugin,
            "preset-default",
            extractCSSPlugin,
        ],
    },
});