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 to avoid common problems such as downloading unnecessary font files.

要启用此功能,请配置一个至少包含一种字体的 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 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

Astro 重新导出了大多数 unifont 提供程序。以下内容已内置支持:

¥Astro re-exports most unifont providers. The following 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: process.env.ADOBE_ID })

你也可以为任何 unifont 提供程序使用 创建自定义 Astro 字体提供程序

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

¥<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
默认:false

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

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

如果 fallbacks 数组中的最后一个字体是 通用字体家族名称,Astro 将尝试使用字体规范生成 优化的回退方案。要禁用此优化,请将 optimizedFallbacks 设置为 false。

¥If the last font in the fallbacks array is a generic family name, Astro will 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.

在底层,这些选项由 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[]
默认:["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "latin"]

¥Type: string[]
Default: ["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "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 字符范围

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

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

¥Type: number | string

A 字体粗细:

¥A font weight:

weight: 200

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

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

weight: "100 900"

类型:"normal" | "italic" | "oblique"

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

A 字体样式:

¥A font style:

style: "normal"

类型:(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"
}
]
}]
}
});

构建你自己的字体提供程序

标题部分 构建你自己的字体提供程序

¥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
    fonts: [{
    provider: fontProviders.myProvider(),
    name: "Custom Font",
    cssVariable: "--font-custom"
    }]

¥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.7 中文网 - 粤ICP备13048890号