In a previous post I wrote about how to use Font Awesome 5’s with Turbolinks. Some of you have asked how you might do something similar but using Stimulus instead of coffeescript. Recently I started a new Rails app using webpacker and stimulus. Here are the steps I used to get this setup working with Font Awesome 5.

The Rails app

rails new myapp --webpack=stimulus

Setting up Font Awesome 5

One of the great things about using FA5 via JS is the ability to only import the icons you’ll actually be using. In this case I only needed the twitter icon.

yarn add @fortawesome/fontawesome
yarn add @fortawesome/fontawesome-free-brands

Create a Stimulus controller

We’re going to create a controller which we’ll attach the body tag in the main layout. This controller will be responsible for importing the needed icons and for telling Font Awesome when they need to be rendered.

Create app/Javascript/Controllers/fa_controller.js

import fontawesome from '@fortawesome/fontawesome'
import faTwitter from '@fortawesome/fontawesome-free-brands/faTwitter'

import { Controller } from 'stimulus'
export default class extends Controller {
  initialize() {
    fontawesome.library.add(faTwitter)
  }
  connect() {
    fontawesome.dom.i2svg()
  }
}

Connect the controller

Now we want to connect the body tag to our controller using an HTML5 data attribute (i.e., <body data-controller='fa'>) like so:

app/views/layouts/application.html.haml

%body{ data: {controller: 'fa' }}

I’m a big fan of Haml so this is my layout but yours may be application.html.erb.

Done

You now have a Rails 5 app with Turbolinks, Stimulus, and Font Awesome 5. 🥑🍞