How to Install FontAwesome with Yarn and Webpacker in Rails 6?
FontAwesome
Font Awesome is a popular collection of icons and symbols that you can use in web development to enhance the visual appeal and functionality of your website or application.
Install FontAwesome via yarn
yarn add @fortawesome/fontawesome-free
Output
Check installation
npm list
Output
Import FontAwesome
In the main javascript file, which is app/javascript/packs/application.js
, add the following:
# app/javascript/packs/application.js
import "@fortawesome/fontawesome-free/css/all"
Output
# app/javascript/packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import 'bootstrap/dist/js/bootstrap'
import 'bootstrap/dist/css/bootstrap'
import "bootstrap"
import "stylesheets/application"
import "channels"
import "@fortawesome/fontawesome-free/css/all"
Rails.start()
Turbolinks.start()
ActiveStorage.start()
The statement import "@fortawesome/fontawesome-free/css/all" is used to import the Font Awesome icon library's CSS file, which includes all the icon styles and definitions, into your JavaScript code. This is typically done in a JavaScript or TypeScript file to ensure that the Font Awesome icons are available and styled properly when used in your web application.
Restart the server
In the terminal emulator:
CTRL + C
rails start
Add an icon
Choose any view page and insert a fontAwesome icon.
# app/views/test/index.html.erb
<h1>Test#index</h1>
<p>Find me in app/views/test/index.html.erb</p>
<i class="far fa-gem fa-spin fa-3x"></i>
Home
Full code:
# app/views/test/index.html.erb
<h1>Test#index</h1>
<p>Find me in app/views/test/index.html.erb</p>
<i class="far fa-gem fa-spin fa-3x"></i>
Home
Check the result
Celebrate
You've made it!
Let's become friends
Final thoughts
I hope this article has been helpful to you. Please feel free to reach out if you have any questions. Your thoughts, suggestions, and corrections are more than welcome.
By the way, don't hesitate to drop your suggestions for new blog articles.
I look forward to seeing you next time.
Subscribe to my newsletter
Read articles from Alexandre Calaça directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alexandre Calaça
Alexandre Calaça
I'm a passionate software developer.