Vite Plugin Magical SVG

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

An all-in-one Vite plugin (v1.9.0) for SVG imports that bundles SVGs into spritesheets, supports tree-shaking, and processes referenced assets. Key differentiators vs alternatives like SVGR or vite-plugin-svg-icons: resolves references (e.g., <image href>) inside SVGs, allows selective exclusion per SVG via query parameters, supports multiple output targets (React, Preact, Vue, Solid, Svelte, Ember, Lit, vanilla DOM), and provides experimental features like recoloring control and width/height normalization. Shipped with TypeScript types, requires Vite >= 3.0.0, and follows a fast release cadence with frequent dependency upgrades.

error Error: Cannot find module 'vite-plugin-magical-svg'
cause Package not installed or module resolution issue.
fix
Run 'npm install vite-plugin-magical-svg' (or yarn/pnpm). For ESM, ensure you are using import syntax.
error TypeError: magicalSvg is not a function
cause Named import used instead of default import.
fix
Change to: import magicalSvg from 'vite-plugin-magical-svg'
error Uncaught SyntaxError: The requested module './icon.svg' does not provide an export named 'default'
cause SVG imported without query suffix; the plugin's virtual module expects a ?component or ?url suffix.
fix
Use: import icon from './icon.svg?component'
breaking v1.7.2: Runtime scripts were not importable due to incorrect export configuration.
fix Upgrade to v1.7.3 or later; v1.7.2 is broken.
breaking v1.7.1: Changed from faux ESM to real dual-build (ESM + CJS). Import paths may need updating.
fix Use default import: import magicalSvg from 'vite-plugin-magical-svg'. No path changes required for most users.
deprecated Importing SVGs without a query suffix (e.g., ?component, ?url) may be deprecated in future versions.
fix Always use explicit query suffix (e.g., ./icon.svg?component) to import SVGs.
gotcha Tree-shaking only works when SVGs are imported statically (not dynamically) and with the ?component suffix.
fix Ensure SVG imports are static: import Icon from './icon.svg?component'
gotcha Sprite generation is disabled during development for HMR performance; SVGs are embedded inline instead.
fix No action needed; sprites are only generated in production builds.
npm install vite-plugin-magical-svg
yarn add vite-plugin-magical-svg
pnpm add vite-plugin-magical-svg

Shows setup with Preact target and usage of an SVG as a component with custom props.

// vite.config.js
import { defineConfig } from 'vite'
import magicalSvg from 'vite-plugin-magical-svg'
import preact from '@preact/preset-vite'

export default defineConfig({
  plugins: [
    magicalSvg({ target: 'preact', svgo: true }),
    preact()
  ]
})

// App.jsx
import MyIcon from './icons/alert.svg?component'

export default function App() {
  return (
    <div>
      <h1>Hello, Magical SVG!</h1>
      <MyIcon width={24} height={24} fill="currentColor" />
    </div>
  )
}