每次呼叫 localFont 或 Google 字體函式時,該字體都會在您的應用程式中作為一個執行個體託管。因此,如果您需要在多個位置使用相同的字體,則應該將其載入到一個位置,並在需要的位置導入相關的字體物件。這是使用字體定義檔完成的。
例如,在應用程式目錄根目錄的 styles 資料夾中建立 fonts.ts 檔案。
然後,如下指定您的字體定義
styles/fonts.ts
TypeScript
import { Inter, Lora, Source_Sans_3 } from'next/font/google'import localFont from'next/font/local'// define your variable fontsconstinter=Inter()constlora=Lora()// define 2 weights of a non-variable fontconstsourceCodePro400=Source_Sans_3({ weight:'400' })constsourceCodePro700=Source_Sans_3({ weight:'700' })// define a custom local font where GreatVibes-Regular.ttf is stored in the styles folderconstgreatVibes=localFont({ src:'./GreatVibes-Regular.ttf' })export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }
您現在可以在程式碼中使用這些定義,如下所示
app/page.tsx
TypeScript
import { inter, lora, sourceCodePro700, greatVibes } from'../styles/fonts'exportdefaultfunctionPage() {return ( <div> <pclassName={inter.className}>Hello world using Inter font</p> <pstyle={lora.style}>Hello world using Lora font</p> <pclassName={sourceCodePro700.className}> Hello world using Source_Sans_3 font with weight 700 </p> <pclassName={greatVibes.className}>My title in Great Vibes font</p> </div> )}