omacranger / fontawesome-subset

Creates subsets of FontAwesome fonts for optimized use on the web.
GNU General Public License v3.0
66 stars 15 forks source link

Include a script for auto-subsetting all the icons in your project #9

Closed RentecTravis closed 3 years ago

RentecTravis commented 3 years ago

I'm using your library (THANK YOU!) and made a script so that in dev we could use the regular fontawesome without having to worry about which icons are or aren't in the subset, and when we build the script discovers all the icons in use and auto-generates a subset.

I think with some improvements could be valuable to anyone who uses this project. Namely, the fact that grep isn't available on all systems should be accounted for.

Script

fa-subset.zip

Since you can't do conditional imports in SCSS, in dev mode we generate a file that just includes the fontawesome lib as normal.

In prod the generated SCSS file references the subsetted font files.

package.json scripts

We use Webpack Encore so something like this worked for us

"scripts": {
    "dev": "npm run fa-subset && encore dev",
    "build": "npm run fa-subset && encore production --progress",
    "fa-subset": "node scripts/fa-subset/index.mjs"
}

In SCSS

// $env is set in webpack.config.js via sass-loader's `additionalOptions` config property
@if not variable-exists(env) or $env == "development" {
    // Use regular fontawesome-pro in dev for doubleplusgood DX
    $fa-font-path: "~@fortawesome/fontawesome-pro/webfonts";
} @else {
    // Use auto-generated subset in production for doubleplusgood UX
    $fa-font-path: "/build/fontawesome/webfonts";
}

// Use self-hosted, subsetted fontawesome
@import "/build/fontawesome/fontawesome.scss";

@import "~@fortawesome/fontawesome-pro/scss/regular";
@import "~@fortawesome/fontawesome-pro/scss/solid";
@import "~@fortawesome/fontawesome-pro/scss/light";
@import "~@fortawesome/fontawesome-pro/scss/duotone";
@import "~@fortawesome/fontawesome-pro/scss/brands";
omacranger commented 3 years ago

I think this exists a little outside the scope of this project, but if you were willing to put it up as a gist or something I think it could probably be linked to for inspiration as it's definitely a good idea if their codebase were to support it.