当サイトは、アフィリエイト広告を利用しています
Gatsbyにemotionのcsspropを導入する方法をまとめる。
下記の環境でGatsbyにemotionを導入する
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は使わない
react用のemotionパッケージ。
CRAやGatsby、Nextなどでemotionを使う時にはインストール
する必要あり。
旧名称は「@emotion/core」。 Emotion 11で名称変更された。
@emotion/coreから@emotion/reactに切り替えたことで
動作がおかしくなることがある。
styed-component っぽく書く場合はこれのインストールが必要。
csspropで書く場合は不要。
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は不要。
BabelでJSXを変換するためのモジュール。Babelでは変換対象のモジュールのことをプリセットと呼びます。
Emotionのコンパイルを最適化するためのプラグイン。
GatsbyやNextでemotionを使う時に使う
yarn add @babel/preset-react @emotion/babel-plugin
.babelrcをプロジェクトルートに配置することで
Gatsbyのbabel設定をカスタムできる。
{"presets": [["@babel/preset-react",{ "runtime": "automatic", "importSource": "@emotion/react" }]],"plugins": ["@emotion/babel-plugin"]}
module.exports = {plugins: [{resolve: `gatsby-plugin-emotion`,options: {// Accepts all options defined by `babel-plugin-emotion` plugin.},},],};
codesandboxで動作確認する
2022/05/22現在ではcodesandboxのgatsbyはbeta版のためアカウントでログインしないと
見れないかもです...