New Astro Fonts API
Astro 5.7 has added a new experimental Fonts API.
I’ve added using this new API to serve the Google font for this blog. The docs for the feature show how simple it can be to use an optimized font. Out of the box, the new feature supports several popular font providers:
- Adobe
- Bunny
- Fontshare
- Fontsource
For example, i am using Source Code Pro from Google. We can add that as provided font to our top level Astro config:
export default defineConf({
+ experimental: {
+ fonts: [{
+ provider: fontProviders.google(),
+ name: "Source Code Pro",
+ cssVariable: "--font-source-code-pro",
+ display: "swap"
+ }]
+ }
}
Usage looks like swapping to the Font
component to our Head
component:
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
-<link rel="preconnect" href="https://fonts.googleapis.com" />
-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
-<link
- href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@200..900&display=swap"
- rel="stylesheet"
-/>
+<Font cssVariable="--font-source-code-pro" preload />
Which will provided the needed tags in the <head>
of the page.
All we need to do consume the provided font is to reference the exposed CSS variable.
In my global.css
:
body {
- font-family: Source Code Pro;
+ font-family: var(--font-source-code-pro);
This new feature seems powerful and flexible. Check out the Fonts API configuration reference for more details!
Happy hacking!