Next.js 谷歌字体未得到应用

问题描述 投票:0回答:1
我正在使用 NextJS(版本 14.2.13)开始一个新项目。我使用以下代码从谷歌字体导入了两种字体:

./app/fonts.ts


import { Montserrat, Open_Sans } from 'next/font/google' export const montserrat = Montserrat({ subsets: ['latin'], variable: '--font-montserrat', display: 'swap', }); export const open_sans = Open_Sans({ subsets: ['latin'], variable: '--font-open-sans', display: 'swap', });
按照官方文档,我导入了字体并将它们添加到根布局中的 

<body>

 标签中:

.app/layout.tsx


import {montserrat, open_sans} from './fonts' import "./globals.css"; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={`${montserrat.variable} ${open_sans.variable} antialiased`}> {children} </body> </html> ); }
但是,有些东西不起作用。

    将字体应用于元素时,未应用字体:

.app/page.tsx


import {montserrat} from "./fonts"; export default function Home() { return ( <> <h1 className={`${montserrat.className}`}>Hello World</h1> </> ); }

    在全局样式表中定义时,变量不存在。这会在 IDE 中引发 eslint 警告,并且浏览器开发工具会返回该变量在检查时未定义。

.app/globals.css


h1 { font-family: var(--font-open-sans); } h6 { font-family: var(--font-montserrat); }
为什么我的字体没有被应用?我要补充一点,我已经阅读了官方文档,但即使严格遵循,它也充其量是缺乏的。

任何帮助将不胜感激。

css next.js tailwind-css
1个回答
0
投票
您已经在字体中指定了变量名称。您只需将变量类添加到

app/layout.ts

:

// add this to <body>: <body className={`${montserrat.variable} ${open_sans.variable}`}> ... </body>
然后在 CSS 文件中使用该变量:

h1 { font-family: var(--font-open-sans); } h6 { font-family: var(--font-montserrat); }
文档:

https://nextjs.org/docs/app/api-reference/components/font#css-variables

© www.soinside.com 2019 - 2024. All rights reserved.