Astro Font 优化项目使用教程
1. 项目介绍
astro-font
是一个开源项目,旨在自动优化您的自定义字体、本地字体、通过任何 CDN 的字体以及 Google 字体,以提高性能。该项目灵感来自于 Next.js 的字体优化。
2. 项目快速启动
安装
首先,您需要将 astro-font
安装到您的项目中。可以使用以下任一命令:
npm install astro-font
# 或者
yarn add astro-font
# 或者
pnpm add astro-font
使用 Google 字体
要在所有页面中使用 Google 字体,请将其添加到 Astro 布局的 <head>
文件中:
import { AstroFont } from "astro-font";
<head>
<AstroFont
config={[
{
src: [],
name: "Poppins",
googleFontsURL: 'https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,600;1,400;1,700&display=swap',
preload: true,
display: "swap",
selector: "body",
fallback: "sans-serif",
},
]}
/>
</head>
使用本地字体
如果您想使用本地字体,可以按照以下方式配置:
import { join } from "node:path";
import { AstroFont } from "astro-font";
<head>
<AstroFont
config={[
{
name: "Afacad",
src: [
{
style: 'normal',
weight: '400',
path: join(process.cwd(), 'public', 'fonts', 'Afacad-Regular.ttf'),
},
{
style: 'medium',
weight: '500',
path: join(process.cwd(), 'public', 'fonts', 'Afacad-Medium.ttf'),
},
],
preload: false,
display: "swap",
selector: "body",
fallback: "sans-serif",
},
]}
/>
</head>
3. 应用案例和最佳实践
使用多个字体
您可以在应用程序中导入和使用多个字体。有两种方法可以实现这一点:
方法一:扩展配置数组
import { join } from "node:path";
import { AstroFont } from "astro-font";
<head>
<AstroFont
config={[
{
name: "Afacad",
src: [
{
style: 'bold',
weight: '700',
path: 'https://fonts.gstatic.com/s/afacad/v1/6NUK8FKMIQOGaw6wjYT7ZHG_zsBBfvLqagk-80KjZfJ_uw.woff2',
},
],
preload: true,
display: "swap",
selector: "body",
fallback: "sans-serif",
},
{
name: "Inter",
src: [
{
weight: '400',
style: 'normal',
path: join(process.cwd(), 'public', 'fonts', 'Inter-Regular.ttf'),
},
],
preload: true,
display: "swap",
selector: "body > span",
fallback: "serif",
},
]}
/>
</head>
配置 CSS 类
您可以使用 selector
属性配置哪些 CSS 类将反映整个 CSS(包括对备用字体的引用):
import { join } from "node:path";
import { AstroFont } from "astro-font";
<AstroFont
config={[
{
name: "Afacad",
src: [
{
style: 'bold',
weight: '700',
path: 'https://fonts.gstatic.com/s/afacad/v1/6NUK8FKMIQOGaw6wjYT7ZHG_zsBBfvLqagk-80KjZfJ_uw.woff2',
},
],
preload: true,
display: "swap",
fallback: "sans-serif",
selector: "custom_class",
},
{
name: "Inter",
src: [
{
weight: '400',
style: 'normal',
path: join(process.cwd(), 'public', 'fonts', 'Inter-Regular.ttf'),
},
],
preload: true,
display: "swap",
fallback: "serif",
selector: "body > span",
},
]}
/>
配置 CSS 变量
您可以使用 cssVariable
属性配置哪些 CSS 变量将反映在文档的 :root
CSS 选择器中:
import { join } from "node:path";
import { AstroFont } from "astro-font";
<AstroFont
config={[
{
name: "Afac