Nuxt Fontaine
適用於 Nuxt 3 的字型度量回退實現
功能
⚠️ @nuxtjs/fontaine
正在積極開發中。⚠️
- 💪 透過使用具有精心製作的字型度量的本地字型回退來減少 CLS。
- ✨ 自動生成字型度量和回退。
- ⚡️ 純 CSS,零執行時開銷。
在 playground 專案中,啟用/停用此模組會使渲染 /
時產生以下差異,無需自定義
之前 | 之後 | |
---|---|---|
CLS | 0.34 | 0.013 |
效能 | 88 | 98 |
下一步
為了獲得最佳效能,您需要內聯所有 CSS,而不僅僅是字型回退規則(此模組會自動處理),否則在樣式表載入時仍會出現佈局偏移(這就是上面數字不為零的原因)。
此 PR 旨在將該功能引入 Nuxt 本身。
安裝
npx nuxi@latest module add fontaine
使用
export default defineNuxtConfig({
modules: ['@nuxtjs/fontaine'],
// If you are using a Google font or you don't have a @font-face declaration
// for a font you're using, you can declare them here.
//
// In most cases this is not necessary.
//
// fontMetrics: {
// fonts: ['Inter', { family: 'Some Custom Font', src: '/path/to/custom/font.woff2' }],
// },
})
就是這樣!
Tailwind CSS
如果您使用 Tailwind CSS 並透過配置檔案使用自定義字型,則需要手動添加回退字型。
import type { Config } from 'tailwindcss'
import { fontFamily } from 'tailwindcss/defaultTheme'
export default <Partial<Config>> {
theme: {
extend: {
fontFamily: {
sans: ['Roboto', 'Roboto fallback', ...fontFamily.sans],
},
},
},
}
工作原理
Nuxt 將掃描您的 @font-face
規則並生成具有正確度量的回退規則。例如
@font-face {
font-family: 'Roboto';
font-display: swap;
src: url('/fonts/Roboto.woff2') format('woff2'), url('/fonts/Roboto.woff') format('woff');
font-weight: 700;
}
/* This will be generated. */
@font-face {
font-family: 'Roboto fallback';
src: local('Segoe UI'), local('Roboto'), local('Helvetica Neue'), local('Arial'), local('Noto Sans');
ascent-override: 92.7734375%;
descent-override: 24.4140625%;
line-gap-override: 0%;
}
然後,無論何時您使用 font-family: 'Roboto'
,Nuxt 都會將回退新增到 font-family
:root {
font-family: 'Roboto';
/* This becomes */
font-family: 'Roboto', 'Roboto fallback';
}
在 Nuxt 之外使用
此模組的核心將在 Nuxt 之外工作,並已分離到一個單獨的庫中:fontaine
。快去看看吧!
💻 開發
- 克隆此倉庫
- 使用
corepack enable
啟用 Corepack - 使用
pnpm install
安裝依賴 - 使用
pnpm dev:prepare
模組 - 執行
pnpm dev
以開發模式啟動 playground
鳴謝
如果沒有這些,這一切都不可能實現
- 來自 capsizecss 的驚人工具和生成的度量
- 來自 Google Aurora 團隊的 Katie Hempenius 和 Kara Erickson 的建議和演算法 - 請參閱 計算字型度量覆蓋的注意事項。
許可證
用 ❤️ 製作
根據 MIT 許可證 釋出。