向 NextJs 13 添加多种本地字体

Dr.*_*ouz 4 javascript fonts reactjs next.js next.js13

我正在尝试将多种本地字体添加到 nextjs 13。文档要对单个文件执行以下操作。

我尝试通过以下方式导入这两个文件:

import '@/styles/globals.css';
import localFont from '@next/font/local';
const myFonts = localFont({
  src: '../public/Fonts/AnultraSlabRegular.ttf',
  variable: '--Anultra-Slab',
});
const myFonts2 = localFont({
  src: '../public/Fonts/IntroRegular.ttf',
  variable: '--Intro-Regular',
});
export default function App({ Component, pageProps }) {
  return (
    <main className={'${myFonts2.className} ${myFonts.className}'}>
      <Component {...pageProps} />
    </main>
  );
}
Run Code Online (Sandbox Code Playgroud)

当将字体系列分配给特定元素时,此方法不起作用。

提前致谢!

Rut*_*ger 7

我不得不多次阅读文档。(因为它使用 Google 字体引用示例中的变量名称。)我花了相当长的时间才发现添加多个类不应该通过使用 className(正如大多数示例使用的那样)应用一种字体来完成,例如;

// Do not use className for importing multiple local fonts
<body className={`bg-black ${nantes.className} ${spezia.className}`}>
  {children}
</body>
Run Code Online (Sandbox Code Playgroud)

但是通过使用这样的变量名称;

// use variable for importing multiple fonts which you can use throughout the application
<body className={`bg-black ${nantes.variable} ${spezia.variable}`}>
  {children}
</body>
Run Code Online (Sandbox Code Playgroud)

完整地说,这就是我现在所拥有的,有效的;

布局.tsx

import localFont from '@next/font/local'

const spezia = localFont({
  src: '../fonts/FaroVariableWeb.woff2', 
  variable: '--font-spezia'
})
const nantes = localFont({
  src: '../fonts/Nantes_Variable_Upright_Web.woff2', 
  variable: '--font-nantes'
})

import './globals.css'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {

  return (
    <html lang="en">
      {/*
        <head /> will contain the components returned by the nearest parent
        head.tsx. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head
      */}
      <head />
      <body className={`bg-black ${nantes.variable} ${spezia.variable}`}>
        {children}
      </body>
    </html>
  )
}
Run Code Online (Sandbox Code Playgroud)

全局.css

@tailwind base;
@tailwind components;
@tailwind utilities;

html, body {
  font-family: var(--font-spezia);
  color:blueviolet;
}

h1 {
  font-family: var(--font-nantes);
  color: aqua;
}
Run Code Online (Sandbox Code Playgroud)

  • 哇非常感谢!他们应该以更明确的方式提及......你救了我! (3认同)