当サイトは、アフィリエイト広告を利用しています

Gatsby(v4)にemotionを導入する方法

作成日:2022月05月22日
更新日:2022年10月03日

Gatsbyにemotionのcsspropを導入する方法をまとめる。

環境

下記の環境でGatsbyにemotionを導入する

  • gatsby : 4.14.1
  • react: 17.0.1
  • @emotion/react: 11.9.0

reactのversionが<6.14.0の場合は対応が異なり
@emotion/babel-preset-css-propを使う ※- @emotion/babel-preset-css-prop参照
今回はreactのversionが>=16.14.0なので@emotion/babel-preset-css-propは使わない

gatsbyでemotionを使うのに必要なパッケージをインストールする。

@emotion/react

react用のemotionパッケージ。
CRAやGatsby、Nextなどでemotionを使う時にはインストール
する必要あり。 旧名称は「@emotion/core」。 Emotion 11で名称変更された。 @emotion/coreから@emotion/reactに切り替えたことで
動作がおかしくなることがある。

@emotion/styled

styed-component っぽく書く場合はこれのインストールが必要。
csspropで書く場合は不要。

yarn
yarn add gatsby-plugin-emotion @emotion/react @emotion/styled

@emotion/coreがEmotion11で@emotion/reactに名称変更されたため emotion-themingを使う場合でも@emotion/reactだけでいい。 ※ emotion-themingは@emotion/react 内に移動された。 styed-componentコンポーネント式の記述で使わない場合は@emotion/styledは不要。

emotionのcssprop使うのに必要なパッケージをインストールする。

@babel/preset-react

BabelでJSXを変換するためのモジュール。Babelでは変換対象のモジュールのことをプリセットと呼びます。

@emotion/babel-plugin

Emotionのコンパイルを最適化するためのプラグイン。 
GatsbyやNextでemotionを使う時に使う

yarn
yarn add @babel/preset-react @emotion/babel-plugin

.babelrcを作成

.babelrcをプロジェクトルートに配置することで
Gatsbyのbabel設定をカスタムできる。

.babelrc
{
"presets": [
[
"@babel/preset-react",
{ "runtime": "automatic", "importSource": "@emotion/react" }
]
],
"plugins": ["@emotion/babel-plugin"]
}

gasby-config.jsにプラグインの設定を追加

gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-emotion`,
options: {
// Accepts all options defined by `babel-plugin-emotion` plugin.
},
},
],
};

動作確認

codesandboxで動作確認する
2022/05/22現在ではcodesandboxのgatsbyはbeta版のためアカウントでログインしないと
見れないかもです...

Gatsby + emotion (cssprops)

参考

参考書籍

新着記事

タグ別一覧
top