如何在NextJS 13中导入自定义Google字体?链接标记不工作

aoyhnmkz  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(385)

我尝试在Nextjs项目中使用Google Fonts*,最新版本为13**,但无法导入Google Fonts(即Poppins)正确。
在过去,我只是将链接标记添加到_document.js_app.js文件中,仅此而已。
我试着这样做,但没有成功:

<Head>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"></link>
  </Head>

在过去,一种替代方法是使用@import在全局CSS样式表上导入Google字体,但这种方法也不起作用:

@import url("https://fonts.googleapis.com/css?family=Poppins:300,400,700");

请让我知道我如何在下一个版本13和更高版本上做到这一点

svgewumm

svgewumm1#

要在Next 13+项目中使用Google字体,您可以按以下方式操作:

  • app/layout.js*
import { Poppins } from 'next/font/google';

const poppins = Poppins({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-poppins',
  weight: ['100', '200', '300', '400', '500', '600', '700', '800', '900']
});

export const metadata = {
  title: 'Page Title',
  description: 'Page Description',
}

export default function RootLayout({ children }) {
  return (
    <html className={`${poppins.variable}`}>
      <body>{children}</body>
    </html>
  )
}

然后在任何CSS文件中你都可以这样使用这种字体

.class {
  font-family: var(--font-poppins);
}

相关问题