Ajit Singh Kamal
Posted on March 15, 2021
Disclaimer: the post is now quite old. Vite has a dedicated react plugin which you can easily configure now to get the intended outcome. The comment section has better snippets to help you :)
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.
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'
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.
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [...],
esbuild: {
jsxFactory: `jsx`,
jsxInject: `import { jsx } from '@emotion/react'`,
}
...
});
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 defaultReact.creatElement
with emotions
jsx` 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'`
Posted on March 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.