Skip to content

实验性字体 API

类型:FontFamily[]

¥Type: FontFamily[]

Added in: astro@5.7.0

此实验性功能允许你通过统一、完全可定制且类型安全的 API 使用来自文件系统和各种字体提供商(例如 Google、Fontsource、Bunny)的字体。

¥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 字体会影响页面加载和渲染时的性能。此 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. See common usage examples.

字体 API 通过下载和缓存字体,确保字体能够从你的网站直接提供,从而提升性能并保护隐私。这可以避免将用户数据发送到第三方网站,并确保所有访问者都能使用一致的字体集。

¥The Fonts API focuses on performance and privacy by downloading and caching fonts so they’re served from your site. This can avoid sending user data to third-party sites, and also ensures that a consistent set of fonts is available to all your visitors.

要启用此功能,请配置一个至少包含一种字体的 experimental.fonts 对象:

¥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"
}]
}
});

然后,在你的 <head> 中添加 <Font /> 组件和站点范围的样式:

¥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>

¥Usage

  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, styles and subsets 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

Astro 重新导出了大多数 unifont 提供程序。你也可以为任何 unifont 提供程序使用 创建自定义 Astro 字体提供程序

¥Astro re-exports most unifont providers. You can also make a custom Astro font provider for any unifont provider.

以下提供程序具有内置支持:

¥The following providers have built-in support:

要使用内置远程提供程序,请将 provider 配置为与所选字体提供程序对应的值:

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

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

将加载为 Astro 配置文件中的环境变量 的 ID 传递给 Adob​​e 字体提供程序。

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

¥Usage examples

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
experimental: {
fonts: [
{
name: "Roboto",
cssVariable: "--font-roboto"
provider: fontProviders.google(),
// Default included:
// weights: [400] ,
// styles: ["normal", "italics"],
// subsets: ["latin"],
// fallbacks: ["sans-serif"],
},
{
name: "Inter",
cssVariable: "--font-inter",
provider: fontProviders.fontsource(),
// Specify weights that are actually used
weights: [400, 500, 600, 700],
// Specify styles that are actually used
styles: ["normal"],
// Download only font files for characters used on the page
subsets: ["latin", "cyrillic"],
},
{
name: "JetBrains Mono",
cssVariable: "--font-jetbrains-mono",
provider: fontProviders.fontsource(),
// Download only font files for characters used on the page
subsets: ["latin", "latin-ext"],
// Use a fallback font family matching the intended appearance
fallbacks: ["monospace"],
},
{
name: "Poppins",
cssVariable: "--font-poppins",
provider: "local",
// Weight and style are not specified so Astro
// will try to infer them for each variant
variants: [
{
src: [
"./src/assets/fonts/Poppins-regular.woff2",
"./src/assets/fonts/Poppins-regular.woff",
]
},
{
src: [
"./src/assets/fonts/Poppins-bold.woff2",
"./src/assets/fonts/Poppins-bold.woff",
]
},
]
}
],
}
});

¥<Font /> component reference

此组件输出样式标签,并可选择输出给定字体系列的预加载链接。

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

它必须导入并添加到你的页面 <head>。这通常在 Head.astro 等组件中完成,该组件用于全局通用的站点布局,但可以根据需要添加到各个页面。

¥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.

示例类型:"--font-roboto" | "--font-comic-sans" | ...

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

Astro 配置中注册的 cssVariable

¥The cssVariable registered in your Astro configuration:

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

类型:boolean | { weight?: string | number; style?: string; subset?: string }[]
默认:false

¥Type: boolean | { weight?: string | number; style?: string; subset?: string }[]
Default: false

是否输出 预加载链接

¥Whether to output preload links or not:

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

启用 preload 指令后,浏览器将在页面加载期间立即开始下载所有可能的字体链接。

¥With the preload directive, the browser will immediately begin downloading all possible font links during page load.

¥Granular preloads

Added in: astro@5.15.0

你可能并非总是需要预加载每个字体链接,因为这可能会阻止加载其他重要资源,或者下载当前页面不需要的字体。

¥You may not always want to preload every font link, as this can block loading other important resources or may download fonts that are not needed for the current page.

要选择性地控制预加载哪些字体文件,你可以提供一个对象数组,该数组描述了要预加载的字体 weightstylesubset 的任意组合。

¥To selectively control which font files are preloaded, you can provide an array of objects describing any combination of font weight, style, or subset to preload.

以下示例将仅预加载 latin 子集中具有 400 字重或 normal 样式的字体文件:

¥The following example will only preload font files with a 400 weight or a normal style in the latin subset:

src/components/Head.astro
---
import { Font } from 'astro:assets';
---
<Font
cssVariable="--font-roboto"
preload={[
{ subset: 'latin', style: 'normal' },
{ weight: '400' },
]}
/>

如果请求的字体粗细在其范围内,则会预加载可变粗细字体文件。例如,当在 preload 对象中指定 400 时,将包含字体粗细为 100 900 的字体文件。

¥Variable weight font files will be preloaded if any weight within its range is requested. For example, a font file for font weight 100 900 will be included when 400 is specified in a preload object.

¥Accessing font data programmatically

getFontData() 函数旨在以编程方式检索底层字体系列数据,例如,在 API 路由 中,或生成你自己的元标签。

¥The getFontData() function is intended for retrieving lower-level font family data programmatically, for example, in an API Route or to generate your own meta tags.

类型:(cssVariable: CssVariable) => FontData[]

¥Type: (cssVariable: CssVariable) => FontData[]

Added in: astro@5.14.0

返回提供的 cssVariableFontData 对象数组,其中包含 srcweightstyle

¥Returns an array of FontData objects for the provided cssVariable, which contains src, weight and style.

以下示例在使用 satori 生成 OpenGraph 图片时,使用 getFontData() 语句从 URL 获取字体缓冲区:

¥The following example uses getFontData() to get the font buffer from the URL when using satori to generate OpenGraph images:

src/pages/og.png.ts
import type{ APIRoute } from "astro"
import { getFontData } from "astro:assets"
import satori from "satori"
export const GET: APIRoute = (context) => {
const data = getFontData("--font-roboto")
const svg = await satori(
<div style={{ color: "black" }}>hello, world</div>,
{
width: 600,
height: 400,
fonts: [
{
name: "Roboto",
data: await fetch(new URL(data[0].src[0].url, context.url.origin)).then(res => res.arrayBuffer()),
weight: 400,
style: "normal",
},
],
},
)
// ...
}

¥Font configuration reference

字体的所有属性都必须在 Astro 配置中配置。某些属性是远程字体和本地字体所共有的,而其他属性则取决于你选择的字体提供商。

¥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.

¥Common properties

以下属性适用于远程字体和本地字体。providernamecssVariable 是必需的。

¥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"
}]
}
});

类型:AstroFontProvider | "local"

¥Type: AstroFontProvider | "local"

字体文件的来源。你可以使用 内置提供程序、编写自己的 自定义提供程序 或设置为 "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"
}]
}
});

类型:string

¥Type: string

字体系列名称,由你的字体提供商标识:

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

name: "Roboto"

类型:string

¥Type: string

你选择的有效 ident,以 CSS 变量的形式提供(例如,以 -- 开头):

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

cssVariable: "--font-roboto"

类型:string[]
默认:["sans-serif"]

¥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: []

至少指定一个与你的字体预期外观相匹配的 通用字体家族名称。Astro 将尝试使用字体规范生成 优化的回退方案。要禁用此优化,请将 optimizedFallbacks 设置为 false。

¥Specify at least a generic family name matching the intended appearance of your font. Astro will then attempt to generate optimized fallbacks using font metrics. To disable this optimization, set optimizedFallbacks to false.

类型:boolean
默认:true

¥Type: boolean
Default: true

生成后备字体时是否启用 Astro 的默认优化。你可以禁用此默认优化以完全控制 fallbacks 的生成方式:

¥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

远程字体有更多配置选项。设置这些以自定义从 字体提供程序 加载的数据,例如,仅下载某些字体粗细或样式。为了获得更精细的控制,可以使用更多 细粒度配置 属性。

¥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. For more control, more granular configuration is available.

在底层,这些选项由 unifont 处理。某些属性可能不受某些提供商支持,并且每个提供商的处理方式可能不同。

¥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.

类型:(number | string)[]
默认:[400]

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

字体粗细 数组。如果你的配置中未指定任何值,则默认仅包含权重 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"]

类型:("normal" | "italic" | "oblique")[]
默认:["normal", "italic"]

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

字体样式 数组:

¥An array of font styles:

styles: ["normal", "oblique"]

类型:string[]
默认:["latin"]

¥Type: string[]
Default: ["latin"]

定义要预加载的 字体子集 列表。

¥Defines a list of font subsets to preload.

subsets: ["latin"]

类型:"auto" | "block" | "swap" | "fallback" | "optional"
默认:"swap"

¥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"

类型:string[]
默认:undefined

¥Type: string[]
Default: undefined

根据特定的 Unicode 字符范围 确定何时必须下载和使用字体。如果页面上的字符与配置的范围匹配,浏览器将下载字体,所有字符均可在页面上使用。要配置单个字体预加载的字符子集,请参阅 subsets 属性。

¥Determines when a font must be downloaded and used based on a specific range of unicode characters. If a character on the page matches the configured range, the browser will download the font and all characters will be available for use on the page. To configure a subset of characters preloaded for a single font, see the subsets property instead.

当你网站的某个部分使用不同的字母表并以单独的字体显示时,这对于本地化非常有用,可以避免不必要的字体下载。例如,一个同时提供英语和日语版本的网站可以阻止浏览器下载不包含 unicodeRange 中提供的任何日语字符的英语版本页面上的日语字体。

¥This can be useful for localization to avoid unnecessary font downloads when a specific part of your website uses a different alphabet and will be displayed with a separate font. For example, a website that offers both English and Japanese versions can prevent the browser from downloading the Japanese font on English versions of the page that do not contain any of the Japanese characters provided in unicodeRange.

unicodeRange: ["U+26"]

类型:string
默认:undefined

¥Type: string
Default: undefined

A 字体拉伸:

¥A font stretch:

stretch: "condensed"

类型:string
默认:undefined

¥Type: string
Default: undefined

控制 印刷字体功能(例如连字、小型大写字母或花饰):

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

featureSettings: "'smcp' 2"

类型:string
默认:undefined

¥Type: string
Default: undefined

可变设置 字体:

¥Font variation settings:

variationSettings: "'xhgt' 0.7"

¥Local font variants

类型:LocalFontFamily["variants"]

¥Type: LocalFontFamily["variants"]

使用本地字体文件时,variants 属性是必需的。每个变体代表一个 @font-face 声明,并需要 weightstylesrc 值。

¥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"]
}
// ...
]
}]
}
});

类型:number | string
默认:undefined

¥Type: number | string
Default: undefined

A 字体粗细:

¥A font weight:

weight: 200

如果关联字体是 可变字体,你可以指定一个粗细范围:

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

weight: "100 900"

如果未设置此值,Astro 默认会尝试根据第一个 source 推断值。

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

类型:"normal" | "italic" | "oblique"
默认:undefined

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

A 字体样式:

¥A font style:

style: "normal"

如果未设置此值,Astro 默认会尝试根据第一个 source 推断值。

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

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

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

sources 字体。它可以是相对于根目录的路径、导入的包或 URL。如果你通过集成注入本地字体,URL 会特别有用:

¥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"]

你还可以通过提供对象来指定 tech

¥You can also specify a tech by providing objects:

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

¥Other properties

以下来自远程字体系列的选项也适用于变体中的本地字体系列:

¥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"
}
]
}]
}
});

¥Granular remote font configuration

Added in: astro@5.15.6

字体系列由字重和样式等属性组合定义(例如 weights: [500, 600]styles: ["normal", "bold"]),但你可能只想下载这些属性的特定组合。

¥A font family is defined by a combination of properties such as weights and styles (e.g. weights: [500, 600] and styles: ["normal", "bold"]), but you may want to download only certain combinations of these.

为了更好地控制下载哪些字体文件,你可以多次指定相同的字体(即具有相同的 cssVariablenameprovider 属性),并使用不同的组合。Astro 将合并结果并仅下载所需文件。例如,你可以下载普通的 500600,同时只下载斜体 500

¥For greater control over which font files are downloaded, you can specify the same font (ie. with the same cssVariable, name, and provider properties) multiple times with different combinations. Astro will merge the results and download only the required files. For example, it is possible to download normal 500 and 600 while downloading only italic 500:

astro.config.mjs
import { defineConfig, fontProviders } from "astro/config"
export default defineConfig({
experimental: {
fonts: [
{
name: "Roboto",
cssVariable: "--roboto",
provider: fontProviders.google(),
weights: [500, 600],
styles: ["normal"]
},
{
name: "Roboto",
cssVariable: "--roboto",
provider: fontProviders.google(),
weights: [500],
styles: ["italic"]
}
]
}
})

¥Build your own font provider

如果你不想使用 内置提供程序(例如,你想使用第三方统一字体提供商或为私有注册表构建某些内容),你可以自行构建。

¥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.

Astro 字体提供程序由两部分组成:配置对象和实际实现。

¥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
    import { defineConfig } from "astro/config";
    import { myProvider } from "./provider/config";
    export default defineConfig({
    experimental: {
    fonts: [{
    provider: myProvider(),
    // ...
    }]
    }
    });

¥Caching

Fonts API 缓存实现旨在在开发中实用,在生产中高效。在构建过程中,字体文件会被复制到 _astro/fonts 输出目录,以便它们能够从静态资源的 HTTP 缓存中受益(通常为一年)。

¥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).

要在开发过程中清除缓存,请删除 .astro/fonts 目录。要清除构建缓存,请删除 node_modules/.astro/fonts 目录。

¥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

有关完整详细信息和对此实验性 API 提供反馈,请参阅 字体 RFC

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

Astro v5.16 中文网 - 粤ICP备13048890号