Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vite - Separate chunk for fonts

I am building a library that contains components and some shared CSS, like a design system.

The problem is that it is not separating the fonts in different chunks, instead, it is inlining them in the font as base 64, so the CSS file gets huge!

// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  build: {
    lib: {
      entry: resolve(__dirname, 'src/index.ts'),
      name: 'design-system',
    },
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: {
          vue: 'Vue',
        },
      },
    },
  },
  resolve: {
    alias: [
      { find: '@', replacement: '/src' },
    ],
  },
});

I already tried to place it in root/public, but it didn't work.

I have a file _fonts.css which import fonts like so

@font-face {
  font-family: Inter;
  src: url('/public/fonts/Inter-Regular.ttf') format('truetype');
  font-weight: 400;
}

And then I have a main.scss that imports it

// main.scss
@import 'normalize';
@import 'themes';
@import 'fonts';

Any idea on how to split it?

like image 295
Eduardo Sousa Avatar asked Oct 28 '25 08:10

Eduardo Sousa


1 Answers

I was able to accomplish this in a library we're working on by placing the fonts in the special public directory (see: https://vitejs.dev/guide/assets.html#the-public-directory).

Long story short placing assets in there makes Vite copy them over without any actual transformation and/or renaming.

First of all place your font files in public/fonts/.

Then add the following to vite.config.ts:

{
  root: './',
  publicDir: 'public',
}

This was necessary although it should be a default setting.

Then my font declaration looks like this:

@font-face {
  font-family: MyFont;
  src: url('./fonts/myfont.woff2');
  font-weight: 200;
}

But - this is for the library mode. In case you're building an app just start the font URL path with / instead of ./.

like image 188
Aleksandar Bencun Avatar answered Oct 30 '25 07:10

Aleksandar Bencun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!