SVGs and Astro

Published on January 3rd, 2025

I have recently started to build this new personal site using Astro. I had started developing it using Astro version 4 but soon after I began so I just recently switched to Astro 5. With Astro 5, comes an experimental feature that features SVGs. The feature allows you to import SVGs and to use them as Astro components.

With Astro 5, you can now import SVG files and use them as components, which makes adding SVGs to your projects way easier. Before this, Astro 4 didn’t have a built-in way to handle SVGs, so you had to rely on clunky workarounds that often added unnecessary client-side JavaScript. This update cuts out the hassle and keeps your code cleaner and faster.

Import Options

Inline

The simplest way to include an SVG on a page is below. This would pass no props to the SVG.

---
import CatSvg from '../../assets/svgs/cat.svg'
---

<CatSvg />

The output is a cleaner SVG with attributes such as xmlns and version stripped out. Importing it this way will allow you to you pass it any standard SVG as a prop. This includes the attributes below.

  • width
  • height
  • fill
  • stroke
  • viewBox
  • role
  • aria-label
  • class

You can also pass it a size attribute which would apply that value to both the width and the height. This is particularly useful for icons that you want to keep uniform in size.

Sprite Mode

Another way to include an SVG is to use the sprite mode. This will allow you to include the SVG multiple times on a page without adding extra weight to the page. This is particularly useful for icons that are used multiple times on a page.

---
import CatSvg from '../../assets/svgs/cat.svg'
---

<CatSvg mode="sprite" />

When you include the SVG in sprite mode, Astro will only include the SVG one time on the page using the symbol tag. Then all subsequent uses of the of that SVG will use the symbol tag to reference the original SVG. This will help keep the page size down and improve performance while still being able to affect the innards of the SVG with custom CSS.

Astro 4

These new features were refreshing after working with Astro 4. In Astro 4, I had to use a workaround to include SVGs. I had to import the SVG as a raw file and then use the Fragment component to render the SVG. This was a bit clunky and not as clean as the new way in Astro 5.

---
import CatSVGFile from '../svgs/cat.svg?raw'
---

<Fragment set:html={CatSVGFile} />

Much thanks for the Astro community for implementing this feature. I read through their proposal discussions for this feature and there is a lot more info there about this feature and their motiviations and goals for this update. I am excited to see what else they have in store.