
Vite + React.jsでEmotionを使いたい
Viteを使ってReact.jsのアプリを開発しているプロジェクトで、Emotionを導入する小ネタです。自分のメ モがてら残しておきます。
話はVite、React.jsといったパッケージがすでに導入済みで、Viteの設定ファイルがある前提で話を進めます。
試した時のバージョンを書いておきます。
- Vite : v2.6.14
- @vitejs/plugin-react : v1.1.0
- Emotion : v11
Emotion導入
yarn add @emotion/react
yarn add -D @emotion/babel-plugin
設定ファイルの変更
vite.configの変更
/**
* vite.config.ts
*/
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig(() => {
return {
// 〜 root, publicDir, base, buid等の設定はここでは割愛します 〜
plugins: [
// Emotionが提供するcssプロパティ等を反映するために必要となる
react({
jsxImportSource: '@emotion/react',
babel: {
plugins: ['@emotion/babel-plugin'],
},
}),
],
}
})
検索すると、viteのesbuildオプションに次のような方法で設定する記事を見かけますが、これは @vitejs/plugin-react-refresh を使っていた頃の設定方法なのでご注意ください。
この辺をよく知らずに設定していて「動かねぇ🤯」となっていたので他の方が同じ轍を踏まないように、あえてここに記しておきます。
/**
* ⚠️ @vitejs/plugin-react-refresh を使っているケースです。
* @vitejs/plugin-react を使うケースではないのでご注意を。
*/
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
export default defineConfig(() => {
return {
// 〜 root, publicDir, base, buid等の設定はここでは割愛します 〜
plugins: [
reactRefresh(),
],
esbuild: {
jsxFactory: 'jsx',
jsxInject: `import { jsx } from '@emotion/react'`
},
}
})
tsconfigの変更
もし、TypeScriptで開発している場合はtsconfigにも設定を記述します。これを設定しない場合は、JSX中でcssプロパティを記述している箇所でエラーになります。
※ 必要箇所を抜粋した内容を載せておきます。
{
"compilerOptions": {
"jsxImportSource": "@emotion/react"
}
}
以上、ちょっとした小ネタでした。