Using Font Awesome icons with Astro

Using Font Awesome icons with Astro


Here’s how to use Font Awesome Javacript API in an Astro page, so that the icons display correctly. The SVG icons will be generated during build-time, so no JS will be required on client side.

  1. Import Font Awesome dependencies:
npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
  1. Use the JavaScript API in your page.astro to generate the icon’s HTML:
---
// Font Awesome
import { library, icon } from "@fortawesome/fontawesome-svg-core";
import { faYoutube } from "@fortawesome/free-brands-svg-icons";
import { faEnvelope, faGamepad } from "@fortawesome/free-solid-svg-icons";

// Declare all the icons you plan on using
library.add(faYoutube, faEnvelope, faGamepad);

// Instantiate the icon with the icon function
const gamepadIcon = icon({ prefix: "fas", iconName: faGamepad.iconName });
---

<h2>
  <!-- Tell Astro to inject the icon's HTML -->
  <Fragment set:html={gamepadIcon.html} />
  Games
</h2>

<style is:global>
  /* Declare a custom CSS class to make the icon look right */
  .svg-inline--fa {
    overflow: visible;
    box-sizing: content-box;
    display: inline-block;
    height: 1em;
    vertical-align: -0.125em;
  }
</style>

Please comment below if you find a quicker solution.

Alternative solution

The project Astro Icon integrates directly with Astro, and lets you inject any icon from Iconify, including the free icons from FontAwesome.


Thumbnail adapted from a photo by Jason Leung on Unsplash.