npm.io
0.3.0 • Published 23h ago

fontless

Licence
MIT
Version
0.3.0
Deps
12
Size
49 kB
Vulns
0
Weekly
0
Stars
2.0K

fontless

npm version npm downloads Github Actions Codecov

Magical plug-and-play font optimization for modern web applications

Features

  • Optimized font loading: Automatically loads and configures fonts with proper fallbacks and preload links.
  • Multiple provider support: Google Fonts, Bunny Fonts, FontShare, FontSource, and more using unifont
  • Zero runtime overhead: Pure CSS solution with no JavaScript required at runtime
  • Metric-based fallbacks: Reduces Cumulative Layout Shift (CLS) by using font metrics from fontaine
  • CSS transformation: Detects font-family usage in your CSS and injects optimized @font-face declarations
  • Framework agnostic: Works with all modern frameworks (Vue, React, Solid, Svelte, Qwik, etc.)

Installation

# npm
npm install fontless

# pnpm
pnpm install fontless

Usage

Add the fontless plugin to your Vite configuration:

// vite.config.js / vite.config.ts
import { defineConfig } from 'vite'
import { fontless } from 'fontless'

export default defineConfig({
  plugins: [
    // ... other plugins
    fontless()
  ],
})
Using fonts in your CSS

Simply use fonts in your CSS as you normally would, and fontless will handle optimization:

/* Your CSS */
.google-font {
  font-family: "Poppins", sans-serif;
}

.bunny-font {
  font-family: "Aclonica", sans-serif;
}

Configuration

You can customize fontless with various options:

fontless({
  // Configure available providers
  providers: {
    google: true,          // Google Fonts
    bunny: true,           // Bunny Fonts
    fontshare: true,       // FontShare
    fontsource: true,      // FontSource
    // Disable a provider
    adobe: false
  },

  // Provider priority order
  priority: ['google', 'bunny', 'fontshare'],

  // Default font settings
  defaults: {
    preload: true, // also accepts { subsets: ['latin'] } or a filter function
    weights: [400, 700],
    styles: ['normal', 'italic'],
    // Fallbacks use category-aware presets from fontaine
    // Override specific generic families as needed
    fallbacks: {
      'sans-serif': ['Arial', 'Helvetica Neue'],
      // serif, monospace, cursive, fantasy, system-ui, etc. use shared defaults
    }
  },

  // Custom font family configurations
  families: [
    // Configure a specific font
    {
      name: 'Poppins',
      provider: 'google',
      weights: [300, 400, 600]
    },
    // Manual font configuration
    {
      name: 'CustomFont',
      src: [{ url: '/fonts/custom-font.woff2', format: 'woff2' }],
      weight: [400]
    }
  ],

  // Asset configuration
  assets: {
    prefix: '/assets/_fonts'
  },

  // Where font metadata and downloaded fonts are cached between builds, defaulting to
  // `node_modules/.cache/fontless/meta`. Accepts a directory (resolved from the Vite
  // root), `{ dir }`, an `unstorage` instance for a custom driver, or `false` to
  // disable persistent caching.
  cache: '.cache/fonts',

  // Experimental features
  experimental: {
    disableLocalFallbacks: false
  }
})
Category-Aware Fallbacks

Fontless uses category-aware fallback presets shared with the fontaine package. These presets provide optimized system fonts for different generic font families:

  • sans-serif: BlinkMacSystemFont, Segoe UI, Helvetica Neue, Arial, Noto Sans
  • serif: Times New Roman, Georgia, Noto Serif
  • monospace: Courier New, Roboto Mono, Noto Sans Mono
  • cursive: Uses handwriting category fallbacks
  • fantasy: Uses display category fallbacks
  • system-ui, ui-serif, ui-sans-serif, ui-monospace: Mapped to corresponding category presets

You can override fallbacks for specific generic families in the defaults.fallbacks configuration while keeping the shared defaults for others. This ensures consistent font fallback behavior across your application and reduces cumulative layout shift (CLS).

Preloading Fonts

Fontless provides an option to select fonts to preload via preload option. For Vite SPA, the selected preload fonts are automatically injected into the HTML.

For SSR meta-frameworks which don't rely on transformIndexHtml plugin hook, you need to manually render preload links on the server. Fontless provides fontless/runtime module for server to access the necessary data for preload links generation, for example:

  • Vanilla
import { preloads } from "fontless/runtime";

function renderHtml() {
  const renderedPreloads = preloads
    .map(
      (attrs) =>
        `<link rel="${attrs.rel}" as="${attrs.as}" href="${attrs.href}" crossorigin="${attrs.crossorigin}">`,
    )
    .join("\n");
  return `\
<html>
  <head>
    ${renderedPreloads}
  </head>
  <body>
    ...
  </body>
</html>
`;
}
import { preloads } from "fontless/runtime"

export const RouterHead = component$(() => {
  return (
    <>
      {preloads.map((l) => (
        <link key={l.href} {...l} />
      ))}
      ...
    </>
  )
})
import { preloads } from 'fontless/runtime'

function Layout() {
  return (
    <html lang="en">
      <head>
        {preloads.map(({crossorigin, ...attrs}) => (
          <link
            key={attrs.href}
            {...attrs}
            crossOrigin={crossorigin}
          />
        ))}
        ...
      </head>
      <body>
        ...
      </body>
    </html>
  )
}
<script lang="ts">
	import { preloads } from "fontless/runtime";
</script>

<svelte:head>
	<link rel="icon" href={favicon} />
	{#each preloads as attrs}
		<link {...attrs} />
	{/each}
</svelte:head>

How It Works

Fontless works by:

  1. Scanning your CSS files for font-family declarations
  2. Resolving fonts through various providers (Google, Bunny, etc.)
  3. Generating optimized @font-face declarations with proper metrics
  4. Adding fallback fonts with correct metric overrides to reduce CLS
  5. Automatically downloading and managing font assets

Development

  • Clone this repository
  • Enable Corepack using corepack enable
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

License

Made with

Published under MIT License.

Keywords