Przejdź do głównej zawartości

Astro Font Provider API

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

Dodane w: astro@6.0.0 Beta

The Fonts API allows you to access fonts in a unified way. Each family requires the use of an Astro Font Provider, which either downloads font files from a remote service or loads local font files from disk.

Astro exports built-in font providers from astro/config:

import { fontProviders } from 'astro/config'

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

Retrieves fonts from Adobe:

provider: fontProviders.adobe({ id: "your-id" })

Pass the Adobe font provider an ID loaded as an environment variable in your Astro config file.

Retrieves fonts from Bunny:

provider: fontProviders.bunny()

Retrieves fonts from Fontshare:

provider: fontProviders.fontshare()

Retrieves fonts from Fontsource:

provider: fontProviders.fontsource()

Retrieves fonts from Google:

provider: fontProviders.google()

The provider comes with the following family-specific options that can be added in the font.options object.

Type: string[]

Allows specifying a list of glyphs to be included in the font for each font family. This can reduce the size of the font file:

{
// ...
provider: fontProviders.google(),
options: {
experimental: {
glyphs: ["a"]
}
}
}

Type: Partial<Record<VariableAxis, ([string, string] | string)[]>>

Allows setting variable axis configuration:

{
// ...
provider: fontProviders.google(),
options: {
experimental: {
variableAxis: {
slnt: [["-15", "0"]],
CASL: [["0", "1"]],
CRSV: ["1"],
MONO: [["0", "1"]],
}
}
}
}

Retrieves fonts from Google Icons:

provider: fontProviders.googleicons()

The provider comes with the following family-specific options that can be added in the font.options object.

Type: string[]

When resolving the new Material Symbols icons, allows specifying a list of glyphs to be included in the font for each font family. This can reduce the size of the font file:

{
// ...
provider: fontProviders.googleicons(),
options: {
experimental: {
glyphs: ["a"]
}
}
}

Retrieves fonts from disk:

provider: fontProviders.local()

The provider requires that variants be defined in the font.options object.

Type: LocalFontFamily["variants"]

The options.variants property is required. Each variant represents a @font-face declaration and requires a src.

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

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
fonts: [{
provider: fontProviders.local(),
name: "Custom",
cssVariable: "--font-custom",
options: {
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
Default: undefined

A font weight:

weight: 200

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

weight: "100 900"

When the value is not set, by default Astro will try to infer the value based on the first source.

Type: "normal" | "italic" | "oblique"
Default: undefined

A font style:

style: "normal"

When the value is not set, by default Astro will try to infer the value based on the first source.

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 font families are also available for local font families within variants:

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
fonts: [{
provider: fontProviders.local(),
name: "Custom",
cssVariable: "--font-custom",
options: {
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 (e.g. you want to use a 3rd-party unifont provider or build something for a private registry), you can build your own.

The preferred method for implementing a custom font provider is to export a function that returns the FontProvider object and takes the configuration as a parameter.

A FontProvider is an object containing required name and resolveFont() properties. It also has optional config, init() and listFonts() properties available.

The FontProvider type accepts a generic for family options.

Type: string

A unique name for the provider, used in logs and for identification.

Type: (options: ResolveFontOptions) => Awaitable<{ fonts: FontFaceData[] } | undefined>

Used to retrieve and return font face data based on the given options.

Type: Record<string, any>
Default: undefined

A serializable object, used for identification.

Type: (context: FontProviderInitContext) => Awaitable<void>
Default: undefined

Optional callback, used to perform any initialization logic.

Type: Storage

Useful for caching.

Type: URL

The project root, useful for resolving local files paths.

Type: () => Awaitable<string[] | undefined>
Default: undefined

Optional callback, used to return the list of available font names.

The following example defines a font provider for a private registry:

font-provider.ts
import type { FontProvider } from "astro";
import { retrieveFonts, type Fonts } from "./utils.js",
export function registryFontProvider(): FontProvider {
let data: Fonts = {}
return {
name: "registry",
init: async () => {
data = await retrieveFonts(token);
},
listFonts: () => {
return Object.keys(data);
},
resolveFont: ({ familyName, ...rest }) => {
const fonts = data[familyName];
if (fonts) {
return { fonts };
}
return undefined;
},
};
}

You can then register this font provider in the Astro config:

astro.config.ts
import { defineConfig } from "astro/config";
import { registryFontProvider } from "./font-provider";
export default defineConfig({
fonts: [{
provider: registryFontProvider(),
name: "Custom",
cssVariable: "--font-custom"
}]
});

You can define an Astro font provider using a unifont provider under the hood:

font-provider.ts
import type { FontProvider } from "astro";
import type { InitializedProvider } from "unifont";
import { acmeProvider } from "@acme/unifont-provider"
export function acmeFontProvider(): FontProvider {
const provider = acmeProvider();
let initializedProvider: InitializedProvider | undefined;
return {
name: provider._name,
async init(context) {
initializedProvider = await provider(context);
},
async resolveFont({ familyName, ...rest }) {
return await initializedProvider?.resolveFont(familyName, rest);
},
async listFonts() {
return await initializedProvider?.listFonts?.();
},
};
}

You can then register this font provider in the Astro config:

astro.config.ts
import { defineConfig } from "astro/config";
import { acmeFontProvider } from "./font-provider";
export default defineConfig({
fonts: [{
provider: acmeFontProvider(),
name: "Custom",
cssVariable: "--font-custom"
}]
});
Pomóż nam Społeczność Zostań sponsorem