LoginSignup
10
5

More than 1 year has passed since last update.

Next.js + Chakra UI でGoogle Fontsのフォントを利用する方法

Last updated at Posted at 2022-02-26

やりたい事

Next.js + Chakra UIのプロジェクトでGoogle Fontsのフォントを利用したい。

やり方

まずは、Google Fontsから使いたいfontのリンクをコピーする。今回は例としてInterを設定します。

<link
  href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
  rel="stylesheet"
/>

コピーしたリンクをHead内に貼り付ける

_app.tsx
const App: React.FC<AppProps> = ({ Component, pageProps }) => {
  return (
    <>
      <Head>
        // 以下を追加
        <link
          href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />
      </Head>
      <ChakraProvider>
          <Component {...pageProps} />
      </ChakraProvider>
    </>
  )
}

ChakraProvider をインポートしている箇所で以下のように theme を上書きする。

_app.tsx
const App: React.FC<AppProps> = ({ 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=Inter:wght@400;500;600;700&display=swap"
          rel="stylesheet"
        />
      </Head>
      <ChakraProvider
        // 以下を追加
        theme={extendTheme({
          fonts: {
            heading: 'Inter, sans-serif;',
            body: 'Inter, sans-serif;',
          },
        })}
      >
        <Box bgColor={'gray.100'}>
          <Component {...pageProps} />
        </Box>
      </ChakraProvider>
    </>
  )
}

最後に next.config.js に以下を追加してGoogle Fontsの読み込みを最適化。

next.config.js
module.exports = {
   // 以下を追加
   optimizeFonts: true,
}

参考にした記事

Next.jsのFont Optimizations(Webフォントの最適化)を試してみる
https://zenn.dev/catnose99/articles/bb943c3dc99d89

Google fonts integration · Discussion #2287 · chakra-ui/chakra-ui
https://github.com/chakra-ui/chakra-ui/discussions/2287

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5