Using webpack 5 with Font Awesome 5

Both projects dont need any lengthy introductions for anyone familiar with web development. Most popular bundler and icons library out there at the time of the writing.

Here’s how to use them together:

Install Font Awesome 5

Install font-awesome using npm.

This is the most maintainable way as npm update will refresh the dependencies for you.

npm install --save @fortawesome/fontawesome-free

Include Font awesome to your scss bundle

Adjust your paths to account for where scss file is located in your project:

//importing font awesome
$fa-font-path: "../../../node_modules/@fortawesome/fontawesome-free/webfonts";
@import "../../../node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss";
@import "../../../node_modules/@fortawesome/fontawesome-free/scss/solid.scss";

You can also use a shorter syntax using tilda (~) prefix:

//importing font awesome
$fa-font-path: "~@fortawesome/fontawesome-free/webfonts";
@import "~@fortawesome/fontawesome-free/scss/fontawesome.scss";
@import "~@fortawesome/fontawesome-free/scss/solid.scss";

Configure webpack to include fonts Inline (do not do this):

This is the most important bit – you have to inform webpack how to treat found font files and so we need to add this under module rules section of webpack config.

However including font awesome inline will grow your css size significantly, you are likely do not want to do this, but for testing purposes and size comparison here we are:

Add these into your loader rules. Note: Asset loaders is a breaking change from webpack v4:

module: {
  //Loaders are evaluated from bottom to top
  rules: [

    //This rule is here to include dependencies inline
    {
        test: /\.(svg|eot|woff|woff2|ttf)$/,
        type: 'asset/inline'
    },
  //...

Configure webpack to include fonts externally:

With this rule fonts will be dumped into a separate directory and browser will fetch them separately from css:

//This rule is here to include font awesome deps as separate font
{
   test: /\.(svg|eot|woff|woff2|ttf)$/,
   type: 'asset/resource',
   generator: {
     //publicPath: '../fonts/',
     filename: 'compiled/fonts/[hash][ext][query]'
   }
},

Use Font Awesome in your html

For example:

<div id="login_wrapper_header">
  <i class="fas fa-shopping-cart"></i> Shopping Is Nice
</div>

Let it compile and enjoy the result:

Tada. Thank you for reading.

2 thoughts on “Using webpack 5 with Font Awesome 5”

    • Armin!

      You’re my saviour! No idea how you got this but have just spent more than 7 hours trying to get fontawesome6 to work after upgrade to webpack 5. You’re solution worked and no-one else’s did!
      You beat chat GPT, stack overflow, Fontawesome and webpack docs !!!
      I can now enjoy my weekend!!
      Thank you!

      Reply

Leave a Comment