1 min read

Webpacker and Tree Shaking Fontawesome

Adding all of Fontawesome to your rails project will cause your application.js to balloon. Here is how to configure tree shaking to just include the icons you are actually going to use
Webpacker and Tree Shaking Fontawesome
Photo by Fabrice Villard / Unsplash

Adding all of Fontawesome to your rails project will cause your application.js to balloon. Here is how to configure tree shaking to just include the icons you are actually going to use.

The adding all of Fontawesome to my Rails project caused my application.js to hit a massive 447 KB. Nobody should have to download half a meg just so I can show them one icon. Fortunately, there's webpacker and tree shaking to fold in just the icon code for the ones we want.

Add the following packages with yarn:

yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons

This will just add the solid icons from the free set. If you want to use the outline or brands from Fontawesome, refer to the package names.

Edit your app/javascripts/packs/application.js:

// If you have the line below
// delete it or comment it out
// import "@fortawesome/fontawesome-free/js/all"

import { config, library, dom } from '@fortawesome/fontawesome-svg-core'
import { faShare as fasFaShare } from '@fortawesome/free-solid-svg-icons'
config.mutateApproach = 'sync'
library.add(fasFaShare)
dom.watch()

This adds the share icon only. If you want to add more, just rinse and repeat. My application.js reduced to just 35 KB.

Fontawesome's documentation on this subject is here.