Require.js
Font Awesome works well with Require.js, especially if you are using Web Fonts. But if you’re using SVG + JS, you’ll need to make a few adjustments.
We’ll cover the step-by-step basics of getting Require.js set up with Font Awesome, adding a style, displaying icons, and accessing Font Awesome’s API.
Step-by-Step
First, create a new directory called myproject
.
- Download Require.js and place it in a
scripts
directory. - Download Font Awesome and copy all the files in the
js
directory intoscripts/vendors/fontawesome
. - Create an empty
scripts/main.js
file. - Create an empty
index.html
file.
After you finish, your directory structure should look something like this:
If you are using Font Awesome Pro, you can download and copy the files the same way. You’ll just have more files since you’ll have all the Font Awesome styles at your fingertips.
Requiring Font Awesome
The first step is to configure Require.js, so that it can find Font Awesome and load a minified version. In your index.html
file, add the following:
Nothing special going on here.
- We use
data-main
and point toscripts/main.js
just like the getting started Require.js docs tell us to. - We set the
src
attribute to the location we’ve installed Require.js.
Now in your scripts/main.js
add:
We start by configuring Require.js to understand that when we reference fontawesome
it should look in vendors/fontawesome
and load the fontawesome.min.js
file.
Open the Project in Your Browser
Load your browser, and open the index.html
file you just created — we recommend Firefox, Chrome, or Safari — and open the Developer Tools to inspect the console.
Console message letting us know FontAwesome was installed
Add a Style and Display an Icons
In your index.html
file, you can add an icon like this:
In your scripts/main.js
file, add the following:
That adds some dependencies to the fontawesome
name using the Require.js shim property. The dependency we will load is the Solid style icons anytime fontawesome
is loaded.
The paths
section of fontawesome/solid
points to the minified version of the Solid style.
Loading the Solid style and displaying an icon
Adding More Icon Styles
But you’ll probably want more than just the Solid icon style. Here’s how to add in other styles. In your index.html
file, you can add an Twitter icon from the Brands style:
And in your scripts/main.js
, you can add any of the styles you plan to use in your project, like this:
You can see the Twitter icon now appears next to the mug:
Adding the Brands style
Accessing Font Awesome’s API
You can also use Font Awesome’s Javascript API to add icons. We’ll need to configure Require.js to export it. In your scripts/main.js
, you use the API like this:
The exports
property instructs Require.js to use the global FontAwesome
name and make it available as the value passed into the require
function callback.
We can then use it to create an icon and add it to the DOM.
Adding an icon using the Font Awesome JS API