LoginSignup
9
5

More than 5 years have passed since last update.

Gatsby.jsでAdobe Fontsを使う

Posted at

概要

GatsbyでWebFontを使う方法を調べてみました。
今回はAdobe Fontsを使っていきます(Google Fontsなどは適宜置き換えて読んでください)

導入

  1. まずはフォントを入れます。
    Adobe Fontsで好きなフォントをアクティベートしてプロジェクトに追加します。
    下のような画面が出るので、kitIdをメモする。
    Screenshot 2018-10-28 16.11.57.png

  2. Gatsbyではindex.htmlに直接scriptを貼ることは推奨されていないので、
    webfontloaderというパッケージを使ってロードします。
    まずは、yarn add webfontloader
    このフォントをロードしたいコンポーネントで(できればLayout系がいいと思います)

    componentDidMount(){
      WebFont.load({
        typekit: {
          id: 'xxxxxx'
        }
      });
    }
    

    これでフォントはロードされます。

  3. gatsby developはこれで通るのですが、gatsby buildはwebpackのビルドの過程でwindow is not definedを吐いて失敗するので、このページの通りに従い、

gatsby-node.js
   exports.onCreateWebpackConfig = ({ stage, loaders, actions}) => {
     if (stage === 'build-html') {
       actions.setWebpackConfig(
         {
           module: {
             rules: [
               {
                 test: /webfontloader/,
                 use: loaders.null()
               }
             ]
           }
         }
       );   
     }
   }

を追加すれば無事にビルドが通ります。ちなみに、Reactのコンポーネント内でwindowdocumentを参照している箇所がある場合も同様のビルド失敗をしますが、その時はwindowが定義されているかどうかをチェックする(typeof)処理を書くことでwebpackコンパイル時に落ちないようになります。

まとめ

Typography.jsと合わせて使うと非常に快適にフォントを扱えるのでおすすめです。

9
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
9
5