LoginSignup
4
1

React + TypeScript + ViteでEmotionが効かない

Posted at

はじめに

Viteを使用してReact + TypeScriptの環境を構築し、$ npm i @emotion/reactでEmotionを入れました。

各tsxファイルで/** @jsxImportSource @emotion/react */を毎回書くのが煩わしかったので、書かずに済む方法をいろいろ試したのでまとめておきます。

環境

  • React 18.2.0
  • TypeScript 5.2.2
  • Vite 5.0.8
  • @emotion/react 11.11.3
  • @vitejs/plugin-react-swc 3.5.0

問題

まずEmotionの公式サイトを見ます。

tsconfig.jsonに以下を書くだけで良さそうです。

tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  }
}

が、これだけでは全然効きませんでした。

検索してみると、@emotion/babel-preset-css-propを入れろという記事も見つかりましたが、上記のEmotionの公式サイトを見る限り、TypeScript4.1以上であればbabel-pluginはいらないはずです。。

@emotion/babel-plugin is completely optional for TypeScript users. If you are not already using Babel, you probably shouldn't add it to your build tooling unless you truly need one of the features offered by @emotion/babel-plugin.

解決

いろいろ調べたところ、vite-plugin-react-swcのGitに答えがありました。

スクリーンショット 2024-01-09 21.38.41.png

vite.config.tsに、JSX factoryがどこからimportされるかを設定する必要がある、ということのようです。

vite.config.ts
plugins: [
    react({
      jsxImportSource: '@emotion/react',
    }),
],

これで無事にEmotionが効きました。

終わりに

軽い気持ちでEmotionを試してみたのですが全然効かず、すごく時間がかかりました。。

参考

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