Using FontAwesome with Rails was really easy with font-awesome-rails
gem. It also had really nice helpers. Thing is this gem depends on Sprokets. I wanted to try the shiny but very light Propshaft to be inline with modern Rails.
I had 2 options:
- Copy the SVG codes individual icons as needed and use them as part of view. (Easy)
- Consigure FontAwesome as part of build process. (Some work, Easy to update)
I went for 2nd route, mainly because I didn't want to store bunch of SVG codes in my main codebase.
The following solution works on a Rails 7 app configured with cssbundling-rails
gem.
First of all, let's install fontawesome
and sass
to package that.
yarn add sass
yarn add @fortawesome/fontawesome-free
I used v6, but if you need v5, specify the version.
Next, create a entrypoint for sass, call it app/assets/stylesheets/fontawesome.scss
:
$fa-font-path: "./webfonts";
@import "@fortawesome/fontawesome-free/scss/regular";
@import "@fortawesome/fontawesome-free/scss/brands";
@import "@fortawesome/fontawesome-free/scss/solid";
@import "@fortawesome/fontawesome-free/scss/fontawesome";
You may comment out any of regular
, brands
and solid
, if you're not using.
The main magic here is the line $fa-font-path: "./webfonts";
. Without this line, propshaft will fail to find the fonts assets.
Now let's add a task for yarn in package.json
to build the files, add the following the scripts
section:
"build:css:fontawesome": "cp -r ./node_modules/@fortawesome/fontawesome-free/webfonts ./app/assets/builds && sass ./app/assets/stylesheets/fontawesome.scss ./app/assets/builds/fontawesome.css --no-source-map --load-path=node_modules --quiet"
Final step, include it in the layout (application.html.erb
or anywhere else):
<%= stylesheet_link_tag "fontawesome", "data-turbo-track": "reload" %>
Now you can build the assets with the following command, and propshaft will heapily serve it:
yarn build:css:fontawesome
One extra step would be adding the command as part of bin/dev
. You can simple add the following line as part of your Procfile.dev
:
fa: yarn build:css:fontawesome --watch
Now, whenever you would run bin/dev
, fontawesome will be compiled for you.
For me, this works. If you have any nicer solution, please let me know in the comments below.
Note: If you already have a SASS setup, you may want to move the content of app/assets/stylesheets/fontawesome.scss
to your application.scss
or your other entrypoint file, instead of creating another entrypoint. That should work fine as well.
What's on your mind?
2 Comments