@tailwindcss/typographyにもダークモードを適用する
以前の記事で少し取り上げたように、本ブログではmarkdownで書いた記事のレイアウトに@tailwindcss/typographyを用いている。
本ブログのダークモード対応を行うのに際して tailwind.config.js にtypography用の設定を追加する必要があったので対応方法をまとめておく。
ダークモード切り替えボタン
- 「Tailwind CSSでダークモード対応をする」で書いたToggleDarkModeコンポーネントを設置
typographyを適用するPostContentコンポーネント
- ↓のように className="prose"を指定するとtypographyのレイアウトが適用される
import React from 'react'
import Markdown from 'markdown-to-jsx'
export const PostContent = ({ content }: Props) => {
  return (
    <div className="max-w-2xl mx-auto">
      <Markdown className="prose">
        {content}
      </Markdown>
    </div>
  )
}- ただし、この状態でダークモードに切り替えてもtypographyのレイアウトは通常配色のままになってしまう
tailwind.config.js設定
- typographyの配色を変更できるようにするために theme.extend.typography設定とvariants.typography設定を追加する
module.exports = {
  purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
  darkMode: 'class',
  theme: {
    extend: {
      typography: (theme) => ({
        DEFAULT: {},
        dark: {
          css: {
            color: theme('colors.gray.200'),
            a: {
              color: theme('colors.gray.200'),
              '&:hover': {
                color: theme('colors.gray.200'),
              },
            },
            'h2 a': {
              color: theme('colors.gray.200'),
            },
            h1: {
              color: theme('colors.gray.200'),
            },
            h2: {
              color: theme('colors.gray.200'),
            },
            h3: {
              color: theme('colors.gray.200'),
            },
            h4: {
              color: theme('colors.gray.200'),
            },
            h5: {
              color: theme('colors.gray.200'),
            },
            h6: {
              color: theme('colors.gray.200'),
            },
            th: {
              color: theme('colors.gray.200'),
            },
            strong: {
              color: theme('colors.gray.200'),
            },
            code: {
              color: theme('colors.gray.200'),
            },
            figcaption: {
              color: theme('colors.gray.200'),
            },
            blockquote: {
              color: theme('colors.gray.200'),
            },
          },
        },
      }),
    },
  },
  variants: {
    typography: ['dark'],
  },
  plugins: [require('@tailwindcss/typography')],
}PostContentにダークモード時のclassを追加
- PostContentコンポーネントのclassに dark:prose-darkを追加する
import React from 'react'
import Markdown from 'markdown-to-jsx'
export const PostContent = ({ content }: Props) => {
  return (
    <div className="max-w-2xl mx-auto">
      <Markdown className="prose dark:prose-dark">
        {content}
      </Markdown>
    </div>
  )
}これで、@tailwindcss/typographyを利用したコンポーネントにもダークモードを適用することができた。