在 Next.js + Tailwind 中加载和使用 Google 字体的最佳方法
我今天正在使用 Next.js 和 tailwindcss 建立一个新项目,并且我必须使用 Roboto 作为字体。
因为它是 Google 字体,所以我正在寻找从外部 URL 加载字体的最佳方法(因为字体可以通过 CDN 获得,所以我不必自己托管它们)。
以下文章对此进行了非常详细的解释:https://csswizardry.com/2020/05/the-fastest-google-fonts。
从本文中您可以得出以下代码片段:
<link rel="preconnect"
href="https://fonts.gstatic.com"
crossorigin />
<!-- [2] -->
<link rel="preload"
as="style"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" />
<!-- [3] -->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"
media="print" onload="this.media='all'" />
<!-- [4] -->
<noscript>
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" />
</noscript>
还请注意,我只包含我将要使用的粗细(400 和 700)来减小我们正在加载的字体的大小。
那么,如何在 Next.js 应用程序中实现上述代码片段呢?
其实很简单!
在你的/pages
文件夹中,应该有一个_document.js/.tsx
文件。
在这个文件中,我们可以轻松地<head>
使用next/head
模块来调整相应部分。Next.js 会在每个页面上应用该代码片段。
import Document, {
DocumentContext,
Html,
Head,
Main,
NextScript,
} from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return (
<Html>
<Head>
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="true"
/>
<link
rel="preload"
as="style"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"
media="print"
onLoad="this.media='all'"
/>
<noscript>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"
/>
</noscript>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
现在 Next.js 部分已经完成。字体正在加载,耶!
接下来也是最后一部分,实际上是在 Tailwind 中使用该字体,并将其应用于我们所有的无衬线文本(因为 Roboto 是无衬线字体)。
这在 Tailwind 中非常简单,只需要扩展默认主题:
const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
theme: {
extend: {
fontFamily: {
sans: ['Roboto', ...defaultTheme.fontFamily.sans],
},
},
},
variants: {
extend: {},
},
plugins: [],
}
我只需要添加对象sans
的属性fontFamily
以包含 Roboto 字体,并添加默认主题中的其他无衬线字体作为后备。
就是这样!使用 Tailwind 优化了 Next.js 应用程序中的字体加载 :-)
尽情享受吧。