Nuxt 3 的字体度量回退实现
⚠️ @nuxtjs/fontaine 正在积极开发中。⚠️
在 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 并通过配置文件使用自定义字体,则需要手动添加回退字体。
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 之外工作,并已分离到一个单独的库中:fontaine。查看一下!
corepack enable 启用 Corepackpnpm install 安装依赖pnpm dev:prepare 模块pnpm dev 以开发模式启动 playground如果没有以下帮助,这一切将不可能实现
用 ❤️ 制作
根据 MIT 许可证 发布。