Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to setup Emotion with typescript jsxImportSource

When looking at the emotion docs, it seams very simple to add it to a react+typescript project. However, I followed the Typescript instructions to add it to a fresh create-react-app project: https://github.com/testerez/cra-ts-emotion/commit/086cc35cda04a1bb72917ccd3a5b79e81e8be1d9

But when I try to use css prop in any way:

    <div>
  <div css={{ color: "red" }}>Hello!</div>
  <div css={css({ color: "red" })}>Hello!</div>
  <div
    css={css`
      color: red;
    `}
  >
    Hello!
  </div>
</div>

Here is the result I get:

<div>
  <div css="[object Object]">Hello!</div>
  <div
    css="You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."
  >
    Hello!
  </div>
  <div
    css="You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."
  >
    Hello!
  </div>
</div>

Here is my test project: https://github.com/testerez/cra-ts-emotion

What did I miss??

like image 649
Tom Esterez Avatar asked Sep 02 '25 03:09

Tom Esterez


2 Answers

You can either add the jsxImportSource pragma to every file, or you can specify it once in tsconfig.json and once in vite.config.ts:

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "jsxImportSource": "@emotion/react",
    "jsx": "react-jsx"
  }
}
// vite.config.ts
export default defineConfig({
  plugins: [react({ jsxImportSource: '@emotion/react' })],
})
like image 101
Tamlyn Avatar answered Sep 04 '25 22:09

Tamlyn


Answered on this github issue:

you need to add /** @jsxImportSource @emotion/react */ to the top of every file where you use the css prop.

like image 20
Tom Esterez Avatar answered Sep 04 '25 21:09

Tom Esterez