DEV Community

Michael Ishri
Michael Ishri

Posted on

Bundle Google Fonts with your NativePHP Mobile application

If your NativePHP mobile application is using Google Fonts, you can improve the speed of your application by bundling the fonts with your application rather than relying on an internet connection.

The simplest way I've found to do this is to use the log1x/laravel-webfonts composer package.

First install it as a dev dependency.

composer require log1x/laravel-webfonts --dev
Enter fullscreen mode Exit fullscreen mode

Then use it's nice TUI to select your font and it's variants.

php artisan webfonts:add
Enter fullscreen mode Exit fullscreen mode

As specified in the documentation, it will download the font, then extract it to your resources/fonts folder and it will also create a resources/css/fonts.css file with the correct (relative) imports.

Finally, you can simply add this to the top of your resources/css/app.css file.

@import './fonts.css';
Enter fullscreen mode Exit fullscreen mode

Now when you build,

  • the font files will be copied to the public/build/assets folder
  • the css imports will be bundles as part of your app.css file

I found the log1x package to be better suited to NativePHP mobile applications because of how simple it makes bundling with Vite and the fact that it uses relative imports for the fonts. These two points are the main pain points with the spatie/laravel-google-fonts for this use case. I'm sure it's just my inexperience, but I found I had to do a heap of custom Vite plugin stuff to make everything work (with the Spatie package).

If you choose to use the Spatie package instead, just note that it doesn't spit out relative paths for the fonts (it will hard code your APP_URL). This is fine for applications running on the web but on NativePHP Mobile we don't want that. Knowing this is important because it took me a long time to realise this was slowing the boot time of my NativePHP Mobile application. Essentially, using the import provided by the package, it was trying to load fonts from http://localhost:8000 and eventually timing out then fetching from Google directly. So any subsequent boots would be fine since it had already been cached. But once I figured out that NativePHP applications "run" on http://127.0.0.1, it was never going to be able to fetch the fonts locally. Once I fixed this, my boot times went from 2-5 seconds to instant.

Please note, I'm not trying to throw shade at the Spatie package / team. I love those guys and the work they do for our community. I'm simply trying to help others that may run into the same problem that I did and to provide a better solution for this use case.

Top comments (0)