Experimental fonts API
Это содержимое пока не доступно на вашем языке.
Type: FontFamily[]
astro@5.7.0
Новое
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:
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>
:
---import { Font } from 'astro:assets';---
<Font cssVariable='--font-roboto' preload />
<style>body { font-family: var(--font-roboto);}</style>
Usage
Section titled Usage-
experimental.fonts
accepts an array of font objects. For each font, you must specify aprovider
, the familyname
, and define acssVariable
to refer to your font.provider
: You can choose from the list of built-in remote providers, build your own custom font provider, or use the local provider to register local font files.name
: Choose a font family supported by your provider.cssVariable
: Must be a valid ident in the form of a CSS variable.
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
andstyles
to download, are available and some will depend on your chosen provider.See the full configuration reference to learn more.
-
Apply styles using the
<Font />
component. It must be imported and added to your page<head>
. Providing the font’scssVariable
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 thecssVariable
:<style>body {font-family: var(--font-roboto);}</style>src/styles/global.css @import 'tailwindcss';@theme {--font-sans: var(--font-roboto);}tailwind.config.mjs /** @type {import("tailwindcss").Config} */export default {content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],theme: {extend: {},fontFamily: {sans: ["var(--font-roboto)"]}},plugins: []};
Available remote font providers
Section titled Available remote font providersAstro 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 })
provider: fontProviders.bunny()
provider: fontProviders.fontshare()
provider: fontProviders.fontsource()
provider: fontProviders.google()
You can also make a custom Astro font provider for any unifont provider.
<Font />
component reference
Section titled <Font /> component referenceThis 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.
cssVariable
Section titled cssVariableExample type: "--font-roboto" | "--font-comic-sans" | ...
The cssVariable
registered in your Astro configuration:
---import { Font } from 'astro:assets';---
<Font cssVariable="--font-roboto" />
preload
Section titled preloadType: boolean
Default: false
Whether to output preload links or not:
---import { Font } from 'astro:assets';---
<Font cssVariable="--font-roboto" preload />
Font configuration reference
Section titled Font configuration referenceAll 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.
Common properties
Section titled Common propertiesThe following properties are available for remote and local fonts. provider
, name
, and cssVariable
are required.
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({ experimental: { fonts: [{ provider: fontProviders.google(), name: "Roboto", cssVariable: "--font-roboto" }] }});
provider
Section titled providerType: 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:
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"
cssVariable
Section titled cssVariableType: string
A valid ident of your choosing in the form of a CSS variable (i.e. starting with --
):
cssVariable: "--font-roboto"
fallbacks
Section titled fallbacksType: 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.
optimizedFallbacks
Section titled optimizedFallbacksType: 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
Remote font properties
Section titled Remote font propertiesFurther 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.
weights
Section titled weightsType: (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"]
styles
Section titled stylesType: ("normal" | "italic" | "oblique")[]
Default: ["normal", "italic"]
An array of font styles:
styles: ["normal", "oblique"]
subsets
Section titled subsetsType: string[]
Default: ["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "latin"]
Defines a list of font subsets to preload.
subsets: ["latin"]
display
Section titled displayType: "auto" | "block" | "swap" | "fallback" | "optional"
Default: "swap"
Defines how a font displays based on when it is downloaded and ready for use:
display: "block"
unicodeRange
Section titled unicodeRangeType: string[]
Default: undefined
Determines the specific range of unicode characters to be used from a font:
unicodeRange: ["U+26"]
stretch
Section titled stretchType: string
Default: undefined
A font stretch:
stretch: "condensed"
featureSettings
Section titled featureSettingsType: string
Default: undefined
Controls the typographic font features (e.g. ligatures, small caps, or swashes):
featureSettings: "'smcp' 2"
variationSettings
Section titled variationSettingsType: string
Default: undefined
Font variation settings:
variationSettings: "'xhgt' 0.7"
Local font variants
Section titled Local font variantsType: 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.
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"] } // ... ] }] }});
weight
Section titled weightType: 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"
style
Section titled styleType: "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"]
src: [new URL("./custom.ttf", import.meta.url)]
src: ["my-package/SomeFont.ttf"]
You can also specify a tech by providing objects:
src: [{ url:"./src/assets/fonts/MyFont.woff2", tech: "color-COLRv1" }]
Other properties
Section titled Other propertiesThe following options from remote font families are also available for local font families within variants:
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" } ] }] }});
Build your own font provider
Section titled Build your own font providerIf 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.
-
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)});};provider/config.ts import { defineAstroFontProvider } from 'astro/config';interface Config {// ...};export function myProvider(config: Config) {return defineAstroFontProvider({entrypoint: new URL('./implementation.js', import.meta.url),config});}; -
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// ...});You can check out the source code for unifont’s providers to learn more about how to create a unifont provider.
-
Add your custom provider to your font configuration.
astro.config.mjs fonts: [{provider: fontProviders.myProvider(),name: "Custom Font",cssVariable: "--font-custom"}]
Caching
Section titled CachingThe 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
Further reading
Section titled Further readingFor full details and to give feedback on this experimental API, see the Fonts RFC.
Reference