当サイトは、アフィリエイト広告を利用しています
Next.js × TypeScriptにCSS in JSのEmotion(css Prop)を導入する
方法を忘備録として残す。
Next.jsでEmotionのcssPropを使えるようにする方法は
があるが、今回はBabelの方で実施する。
※JSXプラグマはEmotionを使うコンポーネント、またはそれを含む親コンポーネントすべてに
JSXプラグマを書く必要があるため、今回は採用しないことにした。
動作確認環境は下記です。
Emotion(css Prop)をNext.jsで動かすのに必要なパッケージと
プラグインをインストールする。
react用のemotionパッケージ。 CRAやGatsby、Nextなどでemotionを使う時にはインストールする
Emotionのコンパイルを最適化するためのプラグイン。 GatsbyやNextでemotionを使う時に使う
yarn add @emotion/react @emotion/babel-plugin
.babelrcを作成してbabelの設定を書く。
{"presets": [["next/babel",{"preset-react": {"runtime": "automatic","importSource": "@emotion/react"}}]],"plugins": ["@emotion/babel-plugin"]}
TypeScriptでなければこれでcss Propsが使えるようになる。
TypeScriptの場合はここまでの状態でEmotionを使おうとすると
エラーになるので型定義を追加してやる。
{"compilerOptions": {"target": "es5","lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,"forceConsistentCasingInFileNames": true,"noEmit": true,"esModuleInterop": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"jsx": "preserve","incremental": true,"types": ["@emotion/react/types/css-prop"],},"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],"exclude": ["node_modules"]}
これでEmotionのcssPropがNext.js × TypeScriptで使えるようになる。
Emotionの使い方については下記でまとめています。
codesandboxでNext.jsにEmotionのcss Propを導入して動作確認してみる。
下記を参考にさせて頂きました。