4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Gatsby.js】グローバル CSS を反映させたいときは、gatsby-browser.js に設定を記述する

Last updated at Posted at 2021-03-28

Gatsby.js 製のサイトにグローバル CSS を使いたい

こんにちは、@ndj です。
表題の通りです。
フォントの設定とか、margin や padding の初期設定をすべてのページ全体に反映させたいときにいちいちコンポーネントごとにスタイルを読み込んだりするのは面倒です。
Gatsby: Standard Styling with Global CSS Filesを確認したところ、方法が見つかったので、備忘録として残しておきます。

環境

  • Gatsby.js: v3.1.1
  • React.js: v17.0.1

結論

  1. グローバル CSS ファイルを作成する
  2. gatsby-browser.js でグローバル CSS ファイルを読み込む記述を追加する

手順

1. グローバル CSS ファイルを作成する

なにはともあれ、まずは CSS ファイルを作成します。
テストがてら body 要素を真っ赤にしておきましょう。

global.css
body {
    background-color: red;
}

2. gatsby-browser.js にグローバル CSS ファイルを読み込む記述を追加する

次は、gatsby-browser.js というファイルに、先ほど作成した global.css を読み込ませます。

Gatsby プロジェクトの root に gatsby-browser.js という名前のファイルを作成します。
そして、以下の記述を追加します。
global.css の場所は適宜確認してください。

gatsby-browser.js
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 についてもっと深く調べた記事なども書いていきたいと思います。
誤字脱字、間違いご指摘などありましたらコメントいただけますと幸いです。
ここまで読んでくださり、ありがとうございました。

Twitter: ndj

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?