Przejdź do głównej zawartości

Experimental fonts API

Ta treść nie jest jeszcze dostępna w Twoim języku.

Type: FontFamily[]

Dodane w: astro@5.7.0 Nowe

This experimental feature allows you to use fonts from your filesystem and various font providers (eg. Google, Fontsource, Bunny) through a unified, fully customizable, and type-safe API.

Web fonts can impact page performance at both load time and rendering time. This API helps you keep your site performant with automatic web font optimizations including preload links, optimized fallbacks, and opinionated defaults to avoid common problems such as downloading unnecessary font files.

To enable this feature, configure an experimental.fonts object with at least one font:

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
experimental: {
fonts: [{
provider: fontProviders.google(),
name: "Roboto",
cssVariable: "--font-roboto"
}]
}
});

Then, add the <Font /> component and site-wide styling in your <head>:

src/components/Head.astro
---
import { Font } from 'astro:assets';
---
<Font cssVariable='--font-roboto' preload />
<style>
body {
font-family: var(--font-roboto);
}
</style>
  1. experimental.fonts accepts an array of font objects. For each font, you must specify a provider, the family name, and define a cssVariable to refer to your font.

    The following example configures the “Roboto” family from Google Fonts:

    astro.config.mjs
    import { defineConfig, fontProviders } from "astro/config";
    export default defineConfig({
    experimental: {
    fonts: [{
    provider: fontProviders.google(),
    name: "Roboto",
    cssVariable: "--font-roboto"
    }]
    }
    });

    More configuration options, such as defining fallback font families and which weights and styles to download, are available and some will depend on your chosen provider.

    See the full configuration reference to learn more.

  2. Apply styles using the <Font /> component. It must be imported and added to your page <head>. Providing the font’s cssVariable is required, and you can optionally output preload links:

    src/components/Head.astro
    ---
    import { Font } from 'astro:assets';
    ---
    <Font cssVariable="--font-roboto" preload />

    This is commonly done in a component such as Head.astro that is used in a common site layout.

    See the full <Font> component reference for more information.

    Since the <Font /> component generates CSS with font declarations, you can reference the font family using the cssVariable:

    <style>
    body {
    font-family: var(--font-roboto);
    }
    </style>

Available remote font providers

Section titled Available remote font providers

Astro re-exports most unifont providers. The following have built-in support:

To use a built-in remote provider, configure provider with the appropriate value for your chosen font provider:

provider: fontProviders.adobe({ id: process.env.ADOBE_ID })

You can also make a custom Astro font provider for any unifont provider.

This component outputs style tags and can optionally output preload links for a given font family.

It must be imported and added to your page <head>. This is commonly done in a component such as Head.astro that is used in a common site layout for global use but may be added to individual pages as needed.

With this component, you have control over which font family is used on which page, and which fonts are preloaded.

Example type: "--font-roboto" | "--font-comic-sans" | ...

The cssVariable registered in your Astro configuration:

src/components/Head.astro
---
import { Font } from 'astro:assets';
---
<Font cssVariable="--font-roboto" />

Type: boolean
Default: false

Whether to output preload links or not:

src/components/Head.astro
---
import { Font } from 'astro:assets';
---
<Font cssVariable="--font-roboto" preload />

All properties of your fonts must be configured in the Astro config. Some properties are common to both remote and local fonts, and other properties are available depending on your chosen font provider.

The following properties are available for remote and local fonts. provider, name, and cssVariable are required.

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
experimental: {
fonts: [{
provider: fontProviders.google(),
name: "Roboto",
cssVariable: "--font-roboto"
}]
}
});

Type: AstroFontProvider | "local"

The source of your font files. You can use a built-in provider, write your own custom provider, or set to "local" to use local font files:

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
experimental: {
fonts: [{
provider: fontProviders.google(),
name: "Roboto",
cssVariable: "--font-roboto"
}]
}
});

Type: string

The font family name, as identified by your font provider:

name: "Roboto"

Type: string

A valid ident of your choosing in the form of a CSS variable (i.e. starting with --):

cssVariable: "--font-roboto"

Type: string[]
Default: ["sans-serif"]

An array of fonts to use when your chosen font is unavailable, or loading. Fallback fonts will be chosen in the order listed. The first available font will be used:

fallbacks: ["CustomFont", "serif"]

To disable fallback fonts completely, configure an empty array:

fallbacks: []

If the last font in the fallbacks array is a generic family name, an optimized fallback using font metrics will be generated. To disable this optimization, set optimizedFallbacks to false.

Type: boolean
Default: true

Whether or not to enable Astro’s default optimization when generating fallback fonts. You may disable this default optimization to have full control over how fallbacks are generated:

optimizedFallbacks: false

Further configuration options are available for remote fonts. Set these to customize the data loaded from your font provider, for example to only download certain font weights or styles.

Under the hood, these options are handled by unifont. Some properties may not be supported by some providers and may be handled differently by each provider.

Type: (number | string)[]
Default: [400]

An array of font weights. If no value is specified in your configuration, only weight 400 is included by default to prevent unnecessary downloads. You will need to include this property to access any other font weights:

weights: [200, "400", "bold"]

If the associated font is a variable font, you can specify a range of weights:

weights: ["100 900"]

Type: ("normal" | "italic" | "oblique")[]
Default: ["normal", "italic"]

An array of font styles:

styles: ["normal", "oblique"]

Type: string[]
Default: ["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "latin"]

Defines a list of font subsets to preload.

subsets: ["latin"]

Type: "auto" | "block" | "swap" | "fallback" | "optional"
Default: "swap"

Defines how a font displays based on when it is downloaded and ready for use:

display: "block"

Type: string[]
Default: undefined

Determines the specific range of unicode characters to be used from a font:

unicodeRange: ["U+26"]

Type: string
Default: undefined

A font stretch:

stretch: "condensed"

Type: string
Default: undefined

Controls the typographic font features (e.g. ligatures, small caps, or swashes):

featureSettings: "'smcp' 2"

Type: string
Default: undefined

Font variation settings:

variationSettings: "'xhgt' 0.7"

Type: LocalFontFamily["variants"]

The variants property is required when using local font files. Each variant represents a @font-face declaration and requires a weight, style, and src value.

Additionally, some other properties of remote fonts may be specified within each variant.

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
experimental: {
fonts: [{
provider: "local",
name: "Custom",
cssVariable: "--font-custom",
variants: [
{
weight: 400,
style: "normal",
src: ["./src/assets/fonts/custom-400.woff2"]
},
{
weight: 700,
style: "normal",
src: ["./src/assets/fonts/custom-700.woff2"]
}
// ...
]
}]
}
});

Type: number | string

A font weight:

weight: 200

If the associated font is a variable font, you can specify a range of weights:

weight: "100 900"

Type: "normal" | "italic" | "oblique"

A font style:

style: "normal"

Type: (string | URL | { url: string | URL; tech?: string })[]

Font sources. It can be a path relative to the root, a package import or a URL. URLs are particularly useful if you inject local fonts through an integration:

src: ["./src/assets/fonts/MyFont.woff2", "./src/assets/fonts/MyFont.woff"]

You can also specify a tech by providing objects:

src: [{ url:"./src/assets/fonts/MyFont.woff2", tech: "color-COLRv1" }]

The following options from remote font families are also available for local font families within variants:

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
experimental: {
fonts: [{
provider: "local",
name: "Custom",
cssVariable: "--font-custom",
variants: [
{
weight: 400,
style: "normal",
src: ["./src/assets/fonts/custom-400.woff2"],
display: "block"
}
]
}]
}
});

If you do not wish to use one of the built-in providers (eg. you want to use a 3rd-party unifont provider or build something for a private registry), you can build your own.

An Astro font provider is made up of two parts: the config object and the actual implementation.

  1. Using the defineAstroFontProvider() type helper, create a function that returns a font provider config object containing:

    • entrypoint: A URL, a path relative to the root, or a package import.
    • config: An optional serializable object passed to the unifont provider.
    provider/config.ts
    import { defineAstroFontProvider } from 'astro/config';
    export function myProvider() {
    return defineAstroFontProvider({
    entrypoint: new URL('./implementation.js', import.meta.url)
    });
    };
  2. Create a second file to export your unifont provider implementation:

    implementation.ts
    import { defineFontProvider } from "unifont";
    export const provider = defineFontProvider("my-provider", async (options, ctx) => {
    // fetch/define your custom fonts
    // ...
    });
  3. Add your custom provider to your font configuration.

    astro.config.mjs
    fonts: [{
    provider: fontProviders.myProvider(),
    name: "Custom Font",
    cssVariable: "--font-custom"
    }]

The Fonts API caching implementation was designed to be practical in development and efficient in production. During builds, font files are copied to the _astro/fonts output directory, so they can benefit from HTTP caching of static assets (usually a year).

To clear the cache in development, remove the .astro/fonts directory. To clear the build cache, remove the node_modules/.astro/fonts directory

For full details and to give feedback on this experimental API, see the Fonts RFC.

Pomóż nam Społeczność Sponsor