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
- Install node.js if you don’t have
- Install fontawesome-subset
npm install --save-dev fontawesome-subset
- 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 fas.js. It will generate optimized font files.
Also, it will create file my_icons.html with html that uses classes. It is needed for css purge.
Edit arrays regularArray and solidArray to include icons you need.
//fa.js
const { fontawesomeSubset } = require("fontawesome-subset");
const fs = require('fs');
const regularArray = [
"star",
"envelope",
];
const solidArray = [
"star",
"search",
];
fontawesomeSubset(
{
regular: regularArray,
solid: solidArray,
},
"fa_subset_files/fa/webfonts"
);
let html = '';
regularArray.forEach(icon => {
html += '<i class="far fa-' + icon + '"></i>';
});
solidArray.forEach(icon => {
html += '<i class="fas fa-' + icon + '"></i>';
});
fs.writeFile('./fa_subset_files/my_icons.html', html, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
For second file we need:
- Copy file
node_modules\@fortawesome\fontawesome-free\css\all.css
to our folderfa_subset_files
- Run
npm install purify-css
- Create folder
fa_subset_files/css
Now we ready to make script that will optimize css.
//facss.js
const purify = require("purify-css");
const content = ["./fa_subset_files/my_icons.html"];
purify(content, ["./fa_subset_files/all.css"], {
minify: true,
output: "./fa_subset_files/fa/css/min.css"
});
So to create icons, we need:
- Edit fa.js to have icons in arrays regularArray and solidArray
- run
node fa.js
- run
node facss.js
Copy your folder /fa_subset_files/fa/
to your website.
I know this is lame, but I’m not in this js ecosystem. This works for me.