I want to use the @emotion/react library so that I can use the css prop like in this example:

            <div
                css={{
                    backgroundColor: 'pink',
                    height: "500px",
                    width: "500px,
                }}
            >
            </div>

However, I do not want to import /** @jsxImportSource @emotion/react */ at the top of every file that is using the css prop. Please provide me a step by step work-around to be able to have a running react project using the css prop without the strange import, using any of the following: create-react-app, create-react-app + typescript, vite, vite + typescript

Thanks you!

1

There are 1 best solutions below

0
On

Using CRACO we can override CRA configuration and include babel plugins/presets.

For create-react-app:

npm i @emotion/react

npm i -D @emotion/babel-plugin @craco/craco

create file called craco.config.js at the root of the project (next to package.json), with the following code:

module.exports = {
    babel: {
        presets: [
            [
                "@babel/preset-react",
                { "runtime": "automatic", "importSource": "@emotion/react" }
            ]
        ],
        plugins: ["@emotion/babel-plugin"]
    }
}

update scripts in package.json:

"scripts": {
-  "start": "react-scripts start",
+  "start": "craco start",
-  "build": "react-scripts build",
+  "build": "craco build",
-  "test": "react-scripts test",
+  "test": "craco test"
-  "eject": "react-scripts eject"
}

for typescript CRA, make sure to include this in tsconfig inside compilerOptions

"jsx": "react-jsx",
"jsxImportSource": "@emotion/react"

Now test your code without imports and it should be working.

<div
    css={{
        backgroundColor: 'pink',
        height: "500px",
        width: "500px",
        '&:hover': {
            backgroundColor: 'green'
        },
        '@media(max-width: 1000px)': {
            backgroundColor: 'blue'
        }
    }}
>