Reysa's avatar
Level 1

Add custom font to Laravel 10 via vite

Hi I'm working on a Laravel 10 project and I'm really new to Vite

I'm trying to add a custom font that doesn't exist in Google fonts and I have to import it to the project using font-face but I've been searching and trying for over 10 hours and couldn't find a way to do that properly yet.

I've tried to import the fonts inside my app.js but fonts wasn't loading properly

Right now I'm doing it like this in my app.scss but it doesn't work on my cpanel host as the routing should be to "public/build" but it's pointing to "resources/fonts" wich returns 404 on the host

@font-face {
    font-family: 'ISans';
    src: url("../fonts/IRANSansWeb.eot") format("eot"), url("../fonts/IRANSansWeb.woff") format("woff"), url("../fonts/IRANSansWeb.ttf") format("truetype");
}

body {
    font-family: 'ISans' !important;
}
0 likes
5 replies
roselle's avatar

I thought Vite would sort of "build" the fonts, but following your message I realized that it didn't (so thank you for that). Fonts work in local, but it's indeed pointing towards resources/fonts. What I would suggest you to do (it works locally on my side, haven't try to deploy it yet) is to move your fonts directory in the public directory and call ../../public/fonts/ in the different url() instead of ../fonts. It should now work both in local and on your host.

sysoutlucas's avatar
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import path from 'path'

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
    ],
    resolve: {
        alias: {
          '~font' : path.resolve(__dirname,'resources/assets/fonts')
        }
      }
});

use in your css

@font-face {
  font-family: "Metropolis";
  src: url("~font/metropolis/Metropolis-Thin.otf");
  font-weight: 100;
  font-style: normal;
}

work to me in laravel 10

3 likes
roselle's avatar

Just found an even better solution than the one I suggested earlier, and that seems to me even easier than sysoutlucas's, thanks to the Laravel doc (vite#blade-processing-static-assets). You can leave your assets in resources and then put:

import.meta.glob([
    '../fonts/**',
]);

in your app.js file. Leave url('../fonts/your-font.ttf') (or /resources/fonts/your-font.ttf I think it would also work) in your css. After running npm run build, I can see in my browser that Vite has changed the url to /build/assets/my-font.ttf (if I'm just running npm run dev, it shows /resources/fonts/my-font.ttf). Hope this helps!

2 likes

Please or to participate in this conversation.