透過 100 多個技巧的集合來學習 Nuxt!

fontaine
@nuxtjs/fontaine

基於字體度量的自動最佳化字體回退

Nuxt Fontaine

npm versionnpm downloadsGithub ActionsCodecov

Nuxt 3 實作的字體度量回退

功能

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

  • 💪 透過使用具有精確字體度量的本地字體回退來減少 CLS。
  • ✨ 自動產生字體度量和回退。
  • ⚡️ 純 CSS,零執行時開銷。

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

之前之後
CLS0.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('BlinkMacSystemFont'), 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 會將回退新增至字體系列

:root {
  font-family: 'Roboto';
  /* This becomes */
  font-family: 'Roboto', 'Roboto fallback';
}

在 Nuxt 外部使用

此模組的核心將在 Nuxt 之外運作,並且已分離為單獨的函式庫:fontaine。快去看看!

💻 開發

  • 複製此儲存庫
  • 使用 corepack enable 啟用 Corepack
  • 使用 pnpm install 安裝依賴套件
  • 使用 pnpm dev:prepare 存根模組
  • 執行 pnpm dev 以在開發模式下啟動 遊樂場

鳴謝

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

授權

用 ❤️ 製作

MIT 授權 下發佈。