Gatsby.js 製のサイトにグローバル CSS を使いたい
こんにちは、@ndj です。
表題の通りです。
フォントの設定とか、margin や padding の初期設定をすべてのページ全体に反映させたいときにいちいちコンポーネントごとにスタイルを読み込んだりするのは面倒です。
Gatsby: Standard Styling with Global CSS Filesを確認したところ、方法が見つかったので、備忘録として残しておきます。
環境
- Gatsby.js: v3.1.1
- React.js: v17.0.1
結論
- グローバル CSS ファイルを作成する
- gatsby-browser.js でグローバル CSS ファイルを読み込む記述を追加する
手順
1. グローバル CSS ファイルを作成する
なにはともあれ、まずは CSS ファイルを作成します。
テストがてら body 要素を真っ赤にしておきましょう。
body {
background-color: red;
}
2. gatsby-browser.js にグローバル CSS ファイルを読み込む記述を追加する
次は、gatsby-browser.js というファイルに、先ほど作成した global.css を読み込ませます。
Gatsby プロジェクトの root に gatsby-browser.js という名前のファイルを作成します。
そして、以下の記述を追加します。
global.css の場所は適宜確認してください。
import './global.css';
//もしくは、
//require('./global.css');
これで OK です!
注意!
もし開発サーバーが動いていたら、再起動が必要です。
1. Ctrl+C を押して停止
2. gatsby develop を実行
gatsby-browser.js とは
Gatsby: Gatsby Browser APIsによると以下のような記述がありました。
Introduction
The file gatsby-browser.js lets you respond to actions within the browser, and wrap your site in additional components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby.
サイト全体をコンポーネントでラップできたりするらしいです。
アナリティクスの API なんかはここに設定するみたいです(訳にあまり自信がないです…)。
だがとりあえず、グローバル CSS を利用する際はあまり深く考える必要はないっぽい。
What is gatsby-browser.js? Don’t worry about this too much and for now, just know that gatsby-browser.js is one of a handful of special files that Gatsby looks for and uses (if they exist). Here, the naming of the file is important. If you do want to explore more now, check out the docs.
Gatsby: Introduction to Styling in Gatsbyより
その他の方法
共有レイアウトコンポーネントを作成する方法もあるみたいです。
参考 Gatsby: Standard Styling with Global CSS Files
参考
Gatsby: Introduction to Styling in Gatsby
Gatsby: Standard Styling with Global CSS Files
Gatsby: Gatsby Browser APIs
さいごに
今後は、gatsby-browser.js についてもっと深く調べた記事なども書いていきたいと思います。
誤字脱字、間違いご指摘などありましたらコメントいただけますと幸いです。
ここまで読んでくださり、ありがとうございました。