DEV Community

Cover image for Using emotionJs with Vite

Using emotionJs with Vite

ajitsinghkamal profile image Ajit Singh Kamal ・2 min read

Vite is the next cool thing everyone's talking about. For the uninitiated, it's a tool that provides a dev server with a blazingly fast refresh(HMR) speed and comes loaded with the Rollup module bundler for generating highly optimized builds.

Most of you would already be familiar with EmotionJs - a very popular CSS-in-JS library. It comes with a react flavor which provides a css prop that greatly enhances the overall developer experience of writing styles in your react component.

emotion's css prop official doc example
An example from the official docs

However, every time we need to use this very convenient CSS prop, we would need to add emotion's custom JSX pragma on the very top of our jsx component.

/** @jsx jsx */
import { jsx } from '@emotion/react'
Enter fullscreen mode Exit fullscreen mode

If you are planning to give Vite a shot - The good news is that you don't need to do any additional tinkering. Emotion will work without any break when using the above approach. But, there is a far better way, with which we can simply avoid importing this chunk of import in all our JSX files.

To do that - you'd need to update the esbuild options in your project's vite.config file.

Alt Text

Vite uses esbuild under the hood for compilation.

  • jsxInject simply set esbuild's --inject transformation option and auto imports the provided module in all .jsx files.

  • jsxFactory overrides the default React.creatElement with emotionsjsx` factory function.

And, that's it. You can now use emotion in all your jsx components by default.

If you want you can also import the css function along with jsx to avoid it importing later in your components to construct serialized style objects.

jsxInject: `import {jsx, css} from '@emotion/react'` 
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

vfonic profile image

Thanks for the tips!

It would help if the code was added using code block rather than an image. People with disabilities might not be able to read the code from the image and it's harder to copy-paste it. :)
And this code is definitely something I'm looking forward to copy-paste rather than try to type in myself (I don't see much benefit from typing and/or memorizing this)

cheapeone profile image
Christopher Cheape

awesome! was just messing with this today

Forem Open with the Forem app