@vitejs/plugin-react-refresh
was migrated into @vitejs/plugin-react
, and many Emotion + Vite tutorials and boilerplates out there became outdated as a result.
The Vite monorepo has an example react-emotion setup, which seems to works quite well. Here's the gist:
1. Install Emotion Dependencies
Make sure you have the following installed:
yarn add @emotion/react
yarn add -D @emotion/babel-plugin
2. Update vite.config.js
The @vitejs/plugin-react
plugin accepts a custom babel config via the babel
option. Here, we add the @emotion/babel-plugin
plugin we just installed.
Also, to be able to use the css
prop in our JSX, we need to instruct @vitejs/plugin-react
to use Emotion's jsx
function instead of the default jsx-runtime when compiling JSX. We do this by setting the jsxImportSource
option to @emotion/react
.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
jsxImportSource: "@emotion/react",
babel: {
plugins: ["@emotion/babel-plugin"],
},
}),
],
});
Optional: TypeScript support
When using Emotion with TypeScript, your editor may complain that css
is not a valid prop. This is because by default, css
is not a recognised prop in React and your TypeScript compiler doesn't know about Emotion. Fix this by instructing TypeScript to use types from Emotion instead:
{
"compilerOptions": {
"jsxImportSource": "@emotion/react"
}
}
Hope this helps!
Top comments (6)
thank you, this saved me a lot of effort
I'm trying to use component selectors in my emotion styles. Did you have any luck doing so?
For example, I have this
OnOffSwitch
component which has some child elements:These styles (anything below
display: inline-block;
) are being ignored now.I've found this, but there's no mention of how to achieve this with Vite: github.com/emotion-js/emotion/issu...
Also this, which throws an error immediately ("Uncaught SyntaxError: missing ) after argument list"):
stackoverflow.com/questions/614352...
Here's my full
vite.config.js
(I use Vite in a Rails app):@vfonic I just spent the last few hours trying to debug this exact scenario! Did you ever find a solution?
I ran across this issue and found that it was caused by Vite doing some extra code injection (github.com/vitejs/vite/issues/9829). It happened when I was trying to bundle emotion as a module. I ended up removing emotion from the module and using it as a dependency at the root of my project.
Thank you very much!
Thank you so much for this ๐
Surprised this isn't in the official Emotion docs yet...