NEXT.js(Next.js) でGoogle fonts を使用する

Next.js

公式のドキュメントを参考に実装したので、備忘録。

Next 単体で使用する(cssフレームワークなし)

Google fonts のパッケージをインストール

npm install @next/fontこれだけで準備は、完了!!

使用したい場所でフォントを呼び出す

import { Noto_Sans_JP, Montserrat } from '@next/font/google'

const jaFont = Noto_Sans_JP;
const enFont = Montserrat;

引数の設定

下記のプロパティを設定できる。

まぁ基本の weight くらいしか使わないと思うけど。

fontFamily: jaFont({ weight: '400' })みたいな感じで書く。

function Noto_Sans_JP(options: {
    weight: '100' | '300' | '400' | '500' | '700' | '900' | Array<'100' | '300' | '400' | '500' | '700' | '900'>;
    style?: 'normal' | Array<'normal'>;
    display?: Display;
    variable?: CssVariable;
    preload?: boolean;
    fallback?: string[];
    adjustFontFallback?: boolean;
    subsets?: Array<'japanese' | 'latin'>;
}): 

css 変数に格納する

css module を使用するときは、便利に使えそう。

import { Inter } from '@next/font/google'
import styles from '../styles/component.module.css'

const inter = Inter({
  variable: '--inter-font',
})

<main className={inter.variable}>
  <p className={styles.text}>Hello World</p>
</main>
.text {
  font-family: var(--inter-font);
  font-weight: 200;
  font-style: italic;
}

Chakra UI でgoogle fonts を使用する

import Head from 'next/head'
import theme from '../theme'
import { ChakraProvider } from '@chakra-ui/react'

import '../../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Head>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Noto+Sans+JP:wght@400;700&display=swap" rel="stylesheet" />
      </Head>
      <ChakraProvider theme={theme}>
        <Component {...pageProps} />
      </ChakraProvider>
    </>
  )
}

export default MyApp
import { extendTheme } from "@chakra-ui/react"

const theme = extendTheme({
  fonts: {
    heading: 'Montserrat, sans-serif;',
    body: 'Noto Sans JP, sans-serif;',
  },
  colors: {
    brand: {
      main: "#FCC05C",
      bg: "#F7D2B0",
      action: "#F8730E",
      denger: "#f7fafc",
      black: "#333333"
    },
  },
})
export default theme
タイトルとURLをコピーしました