dotgirl.net
Typography を使ってテーマを使いつつ Google Fonts を設定してみる

February 12, 2020

GatsbyJS では Typography.js というライブラリを使ってサイトのテーマを適用するのが渋いらしいです。 いまのところ 30 を超えるテーマがあるそうで、それぞれスタイルやフォントが異なります。

こちら でテーマを試したり調整したりできます。

日本語 Google Fonts の適用

どうせなので、美しいウェブフォントを使ってみようということで、Typography.js が提供するテーマに適用する感じで日本語のセットがある Google Fonts を使ってみます。

まずは Typography.js と関連ライブラリ、テーマを npm で install します。

npm install gatsby-plugin-typography react-typography typography typography-theme-github --save

おなじみの gatsby-config.js にプラグインの設定を書きます。pathToConfigModule は Typography.js の設定情報ファイルへのパスを書きます。

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],
}

上記で設定した設定ファイル src/utils/typography を編集します。

src/utils/typography.js
import Typography from 'typography'
import theme from 'typography-theme-github' // テーマのインポート

theme.headerFontFamily = ['M PLUS 1p', 'Roboto', 'serif']
theme.bodyFontFamily = ['M PLUS 1p', 'Roboto', 'serif']
theme.googleFonts = [
  {
    name: 'M+PLUS+1p',
    styles: ['400'],
  }
]

const typography = new Typography(theme)

export default typography

あるいはこういう書き方もアリ。

src/utils/typography.js
import Typography from 'typography'
import theme from 'typography-theme-github' // テーマのインポート

const typography = new Typography({
  ...theme,
  headerFontFamily:  ['M PLUS 1p', 'Roboto', 'serif'],
  bodyFontFamily:  ['M PLUS 1p', 'Roboto', 'serif'],
  googleFonts: [
    {
      name: 'M+PLUS+1p',
      styles: ['400'],
    }
  ],
})

export default typography

Google Fonts + 日本語 でいい感じの日本語フォントを引っ張ってきます。

今日現在で Early Access 対象のフォントは取得 URL が異なるようで、Typography.js が通す Request URL と異なるため、そのままでは使用できませんでした🥺。 (はんなり明朝、こころ明朝、ニコモジ、ニクキュウ)

まとめ

Typography.js のテーマを使用した上で日本語もきれいにしてみました。Typography.js 自体は更に細かなスタイル指定が可能なのでいろいろ試してみようと思います。

Weekly number of page views since last build: 🥰

0hit
    © 2025, Built with Gatsby