透過 100+ 個小技巧學習 Nuxt!

fontaine
@nuxtjs/fontaine

基於字體指標自動優化字體回退

Nuxt Fontaine

npm versionnpm downloadsGithub ActionsCodecov

Nuxt 3 實作的字體指標回退

功能特色

⚠️ @nuxtjs/fontaine 正在積極開發中。 ⚠️

  • 💪 透過使用具有精心設計的字體指標的本地字體回退來減少 CLS。
  • ✨ 自動產生字體指標和回退。
  • ⚡️ 純 CSS,零執行時額外開銷。

在遊樂場專案中,啟用/停用此模組會在渲染 / 時產生以下差異,無需任何自訂

之前之後
CLS (累計版面配置偏移)0.340.013
效能8898

下一步

為了獲得最佳效能,您需要內聯*所有* 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 Stub 模組
  • 執行 pnpm dev 以在開發模式下啟動 遊樂場

鳴謝

若沒有以下協助,這一切將不可能實現

許可證

用 ❤️ 製作

MIT 許可證 下發布。