Font Awesome 5 added support for using the icon library in a variety of different ways. Historically you could use their font and JavaScript files in combination (which meant including every icon, whether you used it or not) or downloaded the icons and import them manually into your project (which was a lot of work!)
Luckily, they have a great development team who decided to support the various use cases. Here at PullRequest, our favorite use is to load only the SVGs we use in our product, minimizing the resulting bundle for our assets. It’s actually super simple.
First, import the Font Awesome dependencies you’ll need for your project. At the minimum, you’ll need to add to add fontawesome-svg-core
Step 1: Add fontawesome-svg-core to your project
yarn add --dev @fortawesome/fontawesome-svg-core
Step 2: Add the Font Awesome libraries you’ll be using
For the free version:
yarn add --dev @fortawesome/free-solid-svg-icons
yarn add --dev @fortawesome/free-regular-svg-icons
yarn add --dev @fortawesome/free-brands-svg-icons
For the Pro version:
The Pro version of Font Awesome is great – and a cheap way to support the project. We highly recommend it.
First we add variables with our license to the root of our package:
# .npmrc file
@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=<YOUR TOKEN GOES HERE>
If you’re signed into the Font Awesome site, you can find your token here.
Next, add the Pro package:
yarn add --dev @fortawesome/pro-light-svg-icons
yarn add --dev @fortawesome/pro-solid-svg-icons
yarn add --dev @fortawesome/pro-regular-svg-icons
yarn add --dev @fortawesome/free-brands-svg-icons
Step 3: Setup Webpack
Configure Webpack the way you want to for your project. You must enable tree-shaking if you want to save space in the resulting bundle.
There are lots of great tutorials on the web on how to do so, such as this great tutorial from netlify
Step 4: Import the SVGs
Within your application bundle, add the following:
import { library, dom } from "@fortawesome/fontawesome-svg-core";
import { faCheck } from "@fortawesome/free-solid-svg-icons/faCheck";
library.add(faCheck);
dom.watch();
Note: without dom.watch()
, automatic replacement of your Font Awesome icons won’t work in the rendered page!
Step 5: Add the icon to your HTML
<i class="fas fa-check"></i>
If we’ve done our job, we should see a check mark on the resulting HTML: