• Stars
    star
    345
  • Rank 118,682 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created 3 months ago
  • Updated 26 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Plug-and-play web font optimization and configuration for Nuxt apps.

npm version npm downloads License Nuxt Volta

Nuxt Fonts

Plug-and-play custom web font optimization and configuration for Nuxt apps.

Features

  • ✨ zero-configuration required
  • πŸ”‘ built-in providers (google, bunny, fontshare, local - more welcome!)
  • πŸ’ͺ custom providers for full control
  • ⏬ local download support (until nuxt/assets lands)
  • ⚑️ automatic font metric optimisation powered by fontaine and capsize
  • πŸ”₯ build/dev time font caching powered by unstorage

πŸ‘‰ See Nuxt Fonts RFC for full details and discussion.

Quick Start

To get started, simply run:

npx nuxi@latest module add @nuxt/fonts

If you don't already have it in your .gitignore, go ahead and add the .data directory:

.data

Then just add a font-family declaration in your CSS:

<template>
  <div>
    Hello Nuxt Fonts!
  </div>
</template>

<style scoped>
div {
  font-family: Roboto, sans-serif;
}
</style>

That's it! Nuxt Fonts will detect this and you should immediately see the web font loaded in your browser. Read more about how it works.

Tip

Even if you're using a preprocessor like TailwindCSS or UnoCSS, Nuxt Fonts should be able to detect and optimize your fonts with no configuration.

Configuration

You do not need to configure Nuxt Fonts but you can do so for finer-grained control.

export default defineNuxtConfig({
  modules: ['@nuxt/fonts'],
  fonts: {
    // You can provide overrides for individual families
    families: [
      // do not resolve this font with any provider from `@nuxt/fonts`
      { name: 'Custom Font', provider: 'none' },
      // only resolve this font with the `google` provider
      { name: 'My Font Family', provider: 'google' },
      // specify specific font data - this will bypass any providers
      { name: 'Other Font', src: 'url(https://example.com/font.woff2)', weight: 'bold' },
    ],
    // The weights, styles, and subsets to generate font face rules for.
    // You can also customize these for a specific family, within `families`.
    defaults: {
      weights: [400],
      styles: ['normal', 'italic'],
      subsets: [
        'cyrillic-ext',
        'cyrillic',
        'greek-ext',
        'greek',
        'vietnamese',
        'latin-ext',
        'latin',
      ]
    },
    // If you use a generic font family like `Roboto, sans-serif`, we will 'translate' that
    // generic family name into one or more font families when generating fallback metrics.
    // You can customize which families we use. (One or two works best.)
    fallbacks: {
      'serif': ['Times New Roman'],
      'sans-serif': ['Arial'],
      'monospace': ['Courier New'],
      // ...
    },
    assets: {
      // The prefix where your fonts will be accessible
      prefix: '/_fonts'
    },
    providers: {
      // you can pass a new custom provider - see 'Writing a custom provider' below
      // for what this file should look like
      custom: '~/providers/custom',
      // Or you can disable a built-in provider
      google: false,
    },
  }
})

How it works

Nuxt Fonts processes all your CSS and does the following things automatically when it encounters a font-family declaration.

  1. Resolves fonts used in CSS. It starts by looking in your public/ directory for font files that match the name, like Roboto.woff2, RobotoBold.ttf, etc. Then it moves on to web font providers like google, bunny and fontshare. Once a provider is found (in this case, probably Google Fonts), we move on to the next step.

  2. Generates and injects @font-face rules for you. We'll generate rules to point your browser to the right source files. They'll be injected into the same CSS where you use the font-family.

    /* If you write something like this: */
    :root {
      font-family: Poppins;
    }
    /* Then Nuxt fonts will add declarations that look like this at the beginning of the CSS file: */
    @font-face {
      font-family: 'Poppins';
      src: local("Poppins"), url("/_fonts/<hash>.woff2") format(woff2);
      font-display: swap;
      unicode-range: U+0000-00FF,U+0131, /* ... */;
      font-weight: 400;
      font-style: normal;
    }
    /* ... plus more font-face declarations for other unicode ranges/weights */
  3. Proxies and caches font requests. Rather than using the original source URLs (to remote servers), we generate rewrites under the /_fonts subpath. When accessed by your browser, we download the font from the remote server and cache it locally.

  4. Creates font fallback metrics. If we have access to the font metrics (ascent, descent, line gap, character width, etc.) then we can generate a fallback @font-face declaration as well. The idea is that we 'morph' a local system font (like Arial or Times New Roman) to be as close as possible to the size of the web font, to decrease layout shift (read more about CLS).

    :root {
      /* This will generate fallbacks for local versions of Helvetica and Arial, adjusted to match Roboto's metrics. */
      font-family: Roboto, Helvetica, Arial;
      /* If you provide a generic family (like serif or sans-serif), we will use a system font from that family. */
      font-family: Merriweather, serif;
    }
  5. Include fonts in build. When you build your project, we'll copy across all the fonts used in your project so you don't need to make any external requests when loading your site. (Any that haven't already been cached in development are downloaded at build time.) Font file names are hashed and Nuxt will serve them with long-lived cache headers.

Font providers

Font providers are designed to be pluggable and extensible, so no matter your setup you should be able to use an existing provider or write your own, and still benefit from core functionality of Nuxt Fonts.

We ship with four built-in providers.

local

The local provider deeply scans your public/ directories (including of your layers) for font files (supporting ttf, woff, woff2, eot or otf extensions).

Then, when you use a font-family in your CSS, we check to see whether it matches one of these files. We also expect font weight, font style and subset to be in the file name, unless they are 'default' values (400 weight, normal style and latin subset).

google

Google Fonts is one of the best known public font APIs.

bunny

Bunny Fonts is provided by bunny.net and is a drop-in Google Fonts compatible API, focusing on privacy.

fontshare

Fontshare is a free font service with 100+ professional-grade fonts from the Indian Type Foundry (ITF).

You should read their terms in full before using a font through fontshare.

Writing a custom provider

The provider API is likely to evolve in the next few releases of Nuxt Fonts, but at the moment it looks like this:

import { defineFontProvider } from '@nuxt/fonts/utils'

export default defineFontProvider({
  async setup () {
    // do some setup
  },
  async resolveFontFaces (fontFamily, defaults) {
    if (fontFamily === 'My Font Family') {
      return {
        fonts: [
          {
            src: [
              { url: 'https://cdn.org/my-font.woff2', format: 'woff2' },
              'https://cdn.org/my-font.woff', // this will be inferred as a `woff` format file
            ],
            weight: 400,
            style: 'normal',
          }
        ]
      }
    }
  }
})

Module authors can also add their own providers (or remove existing ones) in the fonts:providers hook which is called by Nuxt Fonts after all modules have run.

nuxt.hook('fonts:providers', providers => {
  providers.push({
    async setup () {
      /** some setup */
    },
    async resolveFontFaces (fontFamily, defaults) {
      /** resolve font faces */
    }
  })
})

Contributing

  • Clone this repository
  • Enable Corepack using corepack enable
  • Install dependencies using pnpm install
  • Run pnpm dev:prepare to generate type stubs.
  • Use pnpm dev to start playground in development mode.

πŸ“‘ License

Published under the MIT License

More Repositories

1

nuxt

The Intuitive Vue Framework.
TypeScript
51,559
star
2

framework

Old repo of Nuxt 3 framework, now on nuxt/nuxt
10,721
star
3

awesome

A curated list of awesome things related to Nuxt.js
5,014
star
4

vue-meta

Manage HTML metadata in Vue.js components with SSR support
JavaScript
4,064
star
5

create-nuxt-app

Create Nuxt.js App in seconds.
JavaScript
3,451
star
6

ui

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
Vue
3,316
star
7

content

The file-based CMS for your Nuxt application, powered by Markdown and Vue components.
TypeScript
2,976
star
8

devtools

Unleash Nuxt Developer Experience
Vue
2,681
star
9

website-v2

Nuxt 2 Documentation Website
Vue
2,241
star
10

movies

🍿 A TMDB client built with Nuxt 3
Vue
1,818
star
11

vite

⚑ Vite Experience with Nuxt 2
TypeScript
1,385
star
12

image

Plug-and-play image optimization for Nuxt applications.
TypeScript
1,247
star
13

hackernews

HackerNews clone built with Nuxt.
Vue
1,197
star
14

components

Scan and auto import components for Nuxt.js 2.13+
TypeScript
879
star
15

modules

Discover the Nuxt modules to add any CMS, Database, UI, Auth and integrations into your Vue application.
TypeScript
871
star
16

example-auth0

A simple example that shows how to use Nuxt.js with Auth0.
Vue
713
star
17

vercel-builder

Vercel Builder for Nuxt
TypeScript
641
star
18

typescript

TypeScript Support for Nuxt 2
TypeScript
567
star
19

docs

Old Documentation of Nuxt.js πŸ’š - not in use anymore
539
star
20

learn.nuxt.com

[Work in Progress] An interactive tutorial and playground for Nuxt
Vue
492
star
21

starter

Create a new Nuxt project, module, layer or start from a theme with our collection of starters.
382
star
22

eslint-config

ESlint config used for Nuxt
JavaScript
346
star
23

test-utils

πŸ§ͺ Test utilities for Nuxt
TypeScript
273
star
24

assets

🎨 Unified Assets and Templates for Nuxt
HTML
267
star
25

bridge

πŸŒ‰ Experience Nuxt 3 features on existing Nuxt 2 projects
TypeScript
263
star
26

nuxt.com

The Nuxt website, made with Nuxt.
Vue
225
star
27

nuxt.new

Create a new Nuxt project from your address bar.
Vue
225
star
28

http

Universal HTTP Module for Nuxt.js
JavaScript
221
star
29

cli

⚑️ Nuxt Generation CLI Experience.
TypeScript
207
star
30

module-builder

Complete solution to build Nuxt Modules.
TypeScript
202
star
31

nitro-demo

nuxt nitro preview
Vue
187
star
32

telemetry

Nuxt Telemetry
TypeScript
185
star
33

press

[Deprecated] Minimalist Markdown Publishing for Nuxt.js
JavaScript
184
star
34

todomvc

Nuxt.js TodoMVC Example
Vue
146
star
35

examples

Deployed Nuxt examples
TypeScript
134
star
36

eslint-plugin-nuxt

ESLint plugin for Nuxt.js [WIP]
JavaScript
129
star
37

nuxters

Vue
124
star
38

rfcs

RFCs for changes to Nuxt.js
97
star
39

loading-screen

Loading Screen Module for Nuxt.js
JavaScript
90
star
40

scripts

Plug-and-play script optimization for Nuxt applications. (Public Preview)
TypeScript
65
star
41

cli-draft

WIP: CLI for Nuxt.js projects
62
star
42

postcss8

Opt-in to postcss 8 in Nuxt 2 apps.
TypeScript
58
star
43

actions-yarn

Github Actions for yarn
Shell
47
star
44

codesandbox-nuxt

Starter template for CodeSandBox.io
Vue
43
star
45

blueprints

Module for Nuxt.js to create distributable micro-apps
JavaScript
41
star
46

benchmarks

πŸ’¨ Nuxt.js SSR performance Benchmarks
JavaScript
24
star
47

renovate-config-nuxt

Nuxt.js presets for Renovate tool.
18
star
48

nuxt-services-experimental

[WIP] Around realtime services for Nuxt 3
JavaScript
17
star
49

nuxt3-stubs

JavaScript
13
star
50

static

Fast Static Builder
TypeScript
12
star
51

governance

Nuxt Project Governance
12
star
52

babel-preset-app

PSA: this repo has been moved into nuxt.js/nuxt --> https://github.com/nuxt/nuxt.js/tree/dev/packages/babel-preset-app
JavaScript
10
star
53

nuxt-redirects

Nuxt.js redirects app for Netlify
9
star
54

.github

Default community health files for nuxt repositories
4
star