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

【Next.js × TypeScript】Emotionを導入する

作成日:2022月08月06日
更新日:2024年01月22日

Next.js × TypeScriptにCSS in JSのEmotion(css Prop)を導入する
方法を忘備録として残す。
Next.jsでEmotionのcssPropを使えるようにする方法は

  • Babelで設定する
  • JSXプラグマを使う

があるが、今回はBabelの方で実施する。
※JSXプラグマはEmotionを使うコンポーネント、またはそれを含む親コンポーネントすべてに
JSXプラグマを書く必要があるため、今回は採用しないことにした。

環境

動作確認環境は下記です。

  • React: v18.2.0
  • Next: v12.2.3
  • typescript: v4.7.4
  • Emotion: v11.9.3
  • Node.js: v16.16.0

インストール

Emotion(css Prop)をNext.jsで動かすのに必要なパッケージと
プラグインをインストールする。

@emotion/react

react用のemotionパッケージ。 CRAやGatsby、Nextなどでemotionを使う時にはインストールする

@emotion/babel-plugin

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

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

Babelの設定

.babelrcを作成してbabelの設定を書く。

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

TypeScriptでなければこれでcss Propsが使えるようになる。

TypeScriptの型定義を追加する。

TypeScriptの場合はここまでの状態でEmotionを使おうとすると
エラーになるので型定義を追加してやる。

tsconfig.json
{
"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で動作確認する

codesandboxでNext.jsにEmotionのcss Propを導入して動作確認してみる。

Next.js with Emotion

参考

下記を参考にさせて頂きました。

新着記事

タグ別一覧
top