Rails 7 with Font Awesome

·

2 min read

Font Awesome has always been my favorite icon library for React and Rails projects. It is surely easy to use and makes the user interface much more friendly.

I find enough free icons that Font Awesome offers but you can consider the Pro version in case of extra needs.

To get Font Awesome available for my current Rails 7.0.8 project, I need to install it using Import Maps.

Open your terminal, navigate to your rails project, and then run bin/importmap:

./bin/importmap pin @fortawesome/fontawesome-free

And you’ll see the message under the command below

Pinning "@fortawesome/fontawesome-free" to vendor/javascript/@fortawesome/fontawesome-free.js via download from https://ga.jspm.io/npm:@fortawesome/fontawesome-free@6.7.1/js/fontawesome.js

It tells us that it pins the downloaded Font Awesome javascript file in vendor/javascript/ that has recently been downloaded from https://ga.jspm.io/npm:@fortawesome/fontawesome-free@6.7.1/js/fontawesome.js

Inside config/importmap.rb file, you will see a line of code:

pin "@fortawesome/fontawesome-free", to: "@fortawesome--fontawesome-free.js" # @6.7.1

Now change the target to the remote source instead of the downloaded file located in the vendor folder.

pin '@fortawesome/fontawesome-free', to: 'https://ga.jspm.io/npm:@fortawesome/fontawesome-free@6.7.1/js/all.js'

In the final step, you have to import it into application.js.

import '@fortawesome/fontawesome-free';

As you don’t need the file in vendor, you should remove it.

In your view, you can use an icon tag i and CSS class representing an icon. For instance, this is a backlink with text containing an arrow on the left.

<%= link_to cart_path, class: "btn btn-primary px-5 me-5" do %>
    <i class="fa-solid fa-arrow-left"></i>
    Back
<% end %>

You can find more free Font Awesome icons.

References:

https://www.linkedin.com/pulse/how-install-fontawesome-rails-7-using-importmaps-without-habib/