Using Fontawesome 6 with Stimulus/Rails 7

With Rails 6, I’m trying to deploy Fontawesome 6 using Stimulus… however I have no idea how to do. I have been using this https://www.consolelog.io/using-font-awesome-5-with-turbolinks-and-stimulus/ but without success.

Among other things, fontawesome now comes only in one package @fortawesome/fontawesome-free which includes all the icons. But basically solidIcons or faUser or whatever is not defined. Any idea how to do?

import { Controller } from “@hotwired/stimulus”

import fontawesome from ‘@fortawesome/fontawesome-free’

import solidIcons from ‘@fortawesome/fontawesome-free’

// Connects to data-controller=“fontawesome”

export default class extends Controller {

// register icons we want to use in our app

initialize() {

// we can add all icons at once

//fontawesome.library.add(regularIcons)

fontawesome.library.add(solidIcons)

//fontawesome.library.add(solidSvgIcons)

// or we can add icons individually

//fontawesome.library.add([

//  faUser

//])

}

// tell Font Awesome to convert icons every time the controller connects

connect() {

console.log("converting")

fontawesome.dom.i2svg()

}

}

To complete a bit, the following works… but looks ugly (the conversion is executed in the import function)

import { Controller } from "@hotwired/stimulus"
import "@fortawesome/fontawesome-free/js/all.js"

// Connects to data-controller="fontawesome"
export default class extends Controller {
}

I have been trying to solve this same problem, and, in the end, I realized that the best thing to do is just to use font awesome from a CDN.

<script
  defer
  src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js"
  integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ=="
  crossorigin="anonymous"
  referrerpolicy="no-referrer"
></script>

The reason is that adding FontAwesome to your bundle will just make it much bigger for no practical reason. You are not going to interact with it in your JavaScript anyway, so it seems a good idea to load it independently of the rest of your JS.

If for any reason, you prefer not to use a public CDN, you can serve it directly from your vendor directory.

1 Like

I use webpack with css loaders, so my application.js pack just has the following:

import '@fortawesome/fontawesome-free/js/fontawesome'
import '@fortawesome/fontawesome-free/js/solid'

application.js gets the fontawesome js and the css_loader compiles the fontawesome css into applicaition.css which I include with the respective rails helpers.

Yes but you might know that webpack is deprecated :slight_smile:

Webpack is not deprecated, it is webpacker that is deprecated, but instead jsbundling-rails or shakapacker can be used.

1 Like

Indeed you 're right.

I make a gem: