はじめに
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に以下を書くだけで良さそうです。
{
"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に答えがありました。
vite.config.tsに、JSX factoryがどこからimportされるかを設定する必要がある、ということのようです。
plugins: [
react({
jsxImportSource: '@emotion/react',
}),
],
これで無事にEmotionが効きました。
終わりに
軽い気持ちでEmotionを試してみたのですが全然効かず、すごく時間がかかりました。。
参考
