Web 字體預設
通過簡單提供字體名稱,使用來自 Google Fonts、FontShare 的 Web 字體。
查看所有支持的提供商。
安裝
bash
pnpm add -D @unocss/preset-web-fonts
bash
yarn add -D @unocss/preset-web-fonts
bash
npm install -D @unocss/preset-web-fonts
ts
// uno.config.ts
import { defineConfig } from 'unocss'
import presetWebFonts from '@unocss/preset-web-fonts'
import presetUno from '@unocss/preset-uno'
export default defineConfig({
presets: [
presetUno(),
presetWebFonts({ /* 選項 */ }),
],
})
TIP
這個預設已包含在 unocss
包中,你也可以從那裡導入:
ts
import { presetWebFonts } from 'unocss'
提供商
目前支持的提供商:
none
- 不執行任何操作,將字體視為系統字體google
- Google Fontsbunny
- 隱私友好的 Google Fontsfontshare
- ITF 的優質字體服務
INFO
歡迎提交 PR 以添加更多提供商。🙌
自定義獲取函數
使用你自己的函數獲取字體源。
ts
// uno.config.ts
import { defineConfig } from 'unocss'
import presetWebFonts from '@unocss/preset-web-fonts'
import presetUno from '@unocss/preset-uno'
import axios from 'axios'
import ProxyAgent from 'proxy-agent'
export default defineConfig({
presets: [
presetUno(),
presetWebFonts({
// 使用帶有 https 代理的 axios
customFetch: (url: string) => axios.get(url, { httpsAgent: new ProxyAgent('https://localhost:7890') }).then(it => it.data),
provider: 'google',
fonts: {
sans: 'Roboto',
mono: ['Fira Code', 'Fira Mono:400,700'],
},
}),
],
})
選項
provider
- 類型:
WebFontsProviders
- 默認值:
google
Web 字體的提供商服務。
ts
type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none'
fonts
- 類型:
Record<string, WebFontMeta | string | (WebFontMeta | string)[]>
字體。查看示例瞭解更多詳情。
ts
interface WebFontMeta {
name: string
weights?: (string | number)[]
italic?: boolean
/**
* 覆蓋提供商
* @default <匹配根配置>
*/
provider?: WebFontsProviders
}
extendTheme
- 類型:
boolean
- 默認值:
true
擴展主題對象。
themeKey
- 類型:
string
- 默認值:
fontFamily
主題對象的鍵。
inlineImports
- 類型:
boolean
- 默認值:
true
內聯 CSS @import()
。
customFetch
- 類型:
(url: string) => Promise<string>
- 默認值:
undefined
使用你自己的函數獲取字體源。查看自定義獲取函數。
示例
ts
presetWebFonts({
provider: 'google', // 默認提供商
fonts: {
// 這些將擴展默認主題
sans: 'Roboto',
mono: ['Fira Code', 'Fira Mono:400,700'],
// 自定義字體
lobster: 'Lobster',
lato: [
{
name: 'Lato',
weights: ['400', '700'],
italic: true,
},
{
name: 'sans-serif',
provider: 'none',
},
],
},
})
將自動生成以下 CSS:
css
@import url('https://fonts.googleapis.com/css2?family=Roboto&family=Fira+Code&family=Fira+Mono:wght@400;700&family=Lobster&family=Lato:ital,wght@0,400;0,700;1,400;1,700&display=swap');
/* layer: default */
.font-lato {
font-family: "Lato", sans-serif;
}
.font-lobster {
font-family: "Lobster";
}
.font-mono {
font-family: "Fira Code", "Fira Mono", ui-monospace, SFMono-Regular, Menlo,
Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
.font-sans {
font-family: "Roboto", ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans",
sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol",
"Noto Color Emoji";
}