乐闻世界logo
搜索文章和话题

How to import custom fonts in Next JS?

1个答案

1

There are several methods to import custom fonts into a Next.js project. Here, I will detail several common methods and provide examples.

Method 1: Using CSS or Sass

  1. Place the font files: First, place the font files in the fonts folder under the public directory (typically the public folder). For instance, you can place Roboto-Regular.ttf in the public/fonts directory.

  2. Create a CSS file: Create a CSS file in the styles directory, such as fonts.css.

  3. Import the font: Use the @font-face rule in the fonts.css file to import the font. For example:

css
@font-face { font-family: 'Roboto'; src: url('/fonts/Roboto-Regular.ttf') format('truetype'); font-weight: normal; font-style: normal; }
  1. Import the CSS file in _app.js or _app.tsx:
jsx
import '../styles/fonts.css';
  1. Use the font: In any component within the project, you can now use the Roboto font via CSS:
css
body { font-family: 'Roboto', sans-serif; }

Method 2: Using next/head

If you simply want to quickly reference an online font (such as Google Fonts), you can use next/head to add the font link in the head of a specific page or in _app.js.

jsx
import Head from 'next/head'; function MyApp({ Component, pageProps }) { return ( <> <Head> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet" /> </Head> <Component {...pageProps} /> </> ); } export default MyApp;

Use the font directly in CSS, as shown in the CSS example above.

Method 3: Using font loaders (such as fontsource)

If you use npm or yarn, you can choose to use packages like fontsource to manage fonts. This method allows you to manage font dependencies via npm instead of manually downloading font files.

  1. Install the fontsource package:
bash
npm install @fontsource/roboto

Or

bash
yarn add @fontsource/roboto
  1. Import the font in _app.js or _app.tsx:
jsx
import '@fontsource/roboto/400.css'; import '@fontsource/roboto/700.css';
  1. Use the font: Directly use the Roboto font in CSS.

These are several common methods to import custom fonts into a Next.js project. Each method has its use cases, and you can choose the appropriate one based on your project requirements and personal preferences.

2024年6月29日 12:07 回复

你的答案