LoginSignup
1

More than 3 years have passed since last update.

【Gatsby】Typography.jsでNoto Sans JP(Google Fonts)を使う

Last updated at Posted at 2020-08-17

はじめに

gatsby-starter-blogをテンプレートに選ぶと、フォント系の情報はsrc/utils/Typography.jsに保存されます。

Typography.js
import Typography from "typography"
import Wordpress2016 from "typography-theme-wordpress-2016"

Wordpress2016.overrideThemeStyles = () => {
  return {
    "a.gatsby-resp-image-link": {
      boxShadow: `none`,
    },
  }
}

delete Wordpress2016.googleFonts

const typography = new Typography(Wordpress2016)

// Hot reload typography in development.
if (process.env.NODE_ENV !== `production`) {
  typography.injectStyles()
}

export default typography
export const rhythm = typography.rhythm
export const scale = typography.scale

これを改修して、Google Fontsを使えるようにしてみましょう。

1. モジュールのインストール

必要なモジュールをインストールします。

yarn add typography-theme-github

2. テーマを追加する

Wordpress2016を削除して、追加したモジュールを利用するようにします。

Typography.js
import Typography from "typography"
import theme from "typography-theme-github"

const typography = new Typography(theme)

// Hot reload typography in development.
if (process.env.NODE_ENV !== `production`) {
  typography.injectStyles()
}

export default typography
export const rhythm = typography.rhythm
export const scale = typography.scale

3. テーマにNoto Sans JPを追加する

テーマがGoogle FontsのNoto Sans JPを扱えるように、theme.googleFontsを指定します。

Typography.js
// importは省略

theme.googleFonts = [
  {
    name: "Noto+Sans+JP",
    styles: ["400"],
  }
]

const typography = new Typography(theme)
// 以下省略

このようにすることで、ブログでNoto Sans JPが使えるようになります。

4. ヘッダー、ボディそれぞれにNoto Sans JPを指定する

最後に追加したNoto Sans JPを適用しましょう。

Typography.js
// importは省略

theme.googleFonts = [
  {
    name: "Noto+Sans+JP",
    styles: ["400"],
  }
]

theme.headerFontFamily = ["Noto Sans JP"]
theme.bodyFontFamily = ["Noto Sans JP"]

const typography = new Typography(theme)
// 以下省略

これでフォントを指定することができました。

備考

Typography.jsをもう少しちゃんと知ろうとする場合は、Typography.jsによるフォントスタイルの設定まとめがよいかと思います。

たとえばheaderとbodyそれぞれに異なるフォントを指定することも可能です。

Typography.js
import Typography from "typography"
import theme from "typography-theme-github"

theme.headerFontFamily = ["M PLUS 1P"]
theme.bodyFontFamily = ["hannari"]
theme.googleFonts = [
  {
    name: "M+PLUS+1p",
    styles: ["400"],
  },
  { name: "hannari", styles: ["400"] },
]

const typography = new Typography(theme)

// Hot reload typography in development.
if (process.env.NODE_ENV !== `production`) {
  typography.injectStyles()
}

export default typography
export const rhythm = typography.rhythm
export const scale = typography.scale

Google Fontsの種類については、日本語であればGoogle Fonts + 日本語で確認できます。

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
What you can do with signing up
1