How to shrink font-awesome to use only few icons

Updated: 29th January 2023
Tags: css fontawesome

If you use font-awesome, and you don’t like to load 80kb+ for few icons, this guide is for you. Caution: I’m mostly php developer, so this guide is without advanced js stuff.

We will use https://github.com/omacranger/fontawesome-subset to do this

  1. Install node.js if you don’t have
  2. Install fontawesome-subset npm install --save-dev fontawesome-subset
  3. Install fontawesome npm install --save-dev @fortawesome/[email protected]

Note: we use 5.15.4 version because it is much more simple and lighter.
Create file fabuild.js. It will generate optimized font files.

//fabuild.js
const { fontawesomeSubset } = require("fontawesome-subset");
const fs = require("fs");
const purify = require("purify-css");
const path = require("path");

// ====== CONFIG ======
const outputDir = path.resolve(__dirname, "./public/assets/fasubsetv1");
const faCssSource = path.resolve(__dirname, "./node_modules/@fortawesome/fontawesome-free/css/all.css");

// icons you want - this is example, change to what you need
const regularArray = [
    "bookmark",
    "heart",
    "eye",
    "star",
    "envelope",
    "clock",
    "bell"
];

const solidArray = [
    "home",
    "filter",
    "share-alt",
];

const brandsArray = [
    "markdown"
];


// ====== 1. generate font files ======
fontawesomeSubset(
    {
        regular: regularArray,
        solid: solidArray,
        brands: brandsArray
    },
    path.join(outputDir, "webfonts")
);

// ====== 2. generate temporary HTML for purify-css ======
let html = '';
regularArray.forEach(icon => {
    html += `<i class="far fa-${icon}"></i>`;
});
solidArray.forEach(icon => {
    html += `<i class="fas fa-${icon}"></i>`;
});
brandsArray.forEach(icon => {
    html += `<i class="fab fa-${icon}"></i>`;
});

const tempHtmlPath = path.join(outputDir, "tmp.html");
fs.mkdirSync(outputDir, { recursive: true });
fs.writeFileSync(tempHtmlPath, html);

// ====== 3. optimize CSS ======
const cssOutputDir = path.join(outputDir, "css");
fs.mkdirSync(cssOutputDir, { recursive: true });

purify([tempHtmlPath], [faCssSource], {
    minify: true,
    output: path.join(cssOutputDir, "min.css")
});

console.log("FontAwesome subset generated at:", outputDir);

So to create icons, we need:

  1. Edit fa.js to have icons in arrays regularArray and solidArray
  2. run node fabuild.js

It will create folder public/assets/fasubsetv1 with everything needed. When you commit / upload it to server add to header only css file

<link rel="stylesheet" href="/assets/fasubsetv1/css/min.css">