DEV Community

Mehdi Najafi
Mehdi Najafi

Posted on

How to use emotion css prop in vite.

The primary way to style elements with emotion is the css prop.

const Component = () => {
  return (
    <div
      css={{
        backgroundColor: "hotpink",
        "&:hover": {
          color: "lightgreen",
        },
      }}
    >
      This has a hotpink background.
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

1. Install Dependencies

For using css prop in vite project first install @emotion/babel-plugin:

yarn add -D @emotion/babel-plugin
Enter fullscreen mode Exit fullscreen mode

2. Update vite.config.js

Here, we add the @emotion/babel-plugin to @vitejs/plugin-react babel option. Also for using css prop we have to tell vite to use Emotion's jsx function by setting jsxImportSource to @emotion/react.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: "@emotion/react",
      babel: {
        plugins: ["@emotion/babel-plugin"],
      },
    }),
  ],
});

Enter fullscreen mode Exit fullscreen mode

Now you can use css prop in your react app.

TypeScript

If you are using TypeScript in your project first add "jsxImportSource": "@emotion/react" to your tsconfig.json file.

{
  "compilerOptions": {
    // ...
    "jsxImportSource": "@emotion/react"
  }
}
Enter fullscreen mode Exit fullscreen mode

Then for using typed css prop update your vite-env.d.ts.

/// <reference types="vite/client" />
/// <reference types="@emotion/react/types/css-prop" />
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
blair profile image
Blair

Thanks for this!