Back to Emotion

Extract Static

docs/extract-static.mdx

10.0.62.5 KB
Original Source

Static Extraction has been removed from Emotion, this page only exists to explain the decision

requires babel plugin

DEPRECATED

extractStatic is deprecated and will be removed in emotion@10. We recommend disabling extractStatic or using other libraries like linaria or css-literal-loader.

Why is extractStatic being deprecated?

Static extraction was made for earlier versions of emotion which had a very different architecture to the architecture emotion has today. As emotion has gotten more performant and features such as composition have been added, static extraction has become less important. Because most of the community is leveraging the composition and extractStatic is rarely used, the time spent maintaining extractStatic is much higher than the benefits we get from it. Libraries such as linaria and css-literal-loader do static extraction well and the people working on them are focused on this specific problem. As a team, we believe that projects like prepack, when they are ready, will provide a better and more powerful way to pre-compile styles.

The extractStatic option to babel-plugin-emotion allows you to extract styles with no interpolations into external css files. extractStatic is not recommended because it breaks composition and other powerful patterns from libraries like facepaint.

If you want to use dynamic values you must use css variables.

javascript
const Button = styled('button')`
  background-color: var(--bg);
  padding: 10px;
`
<Button style={{ '--bg': props.success ? '#8BC34A' : '#2395f3' }}/>

Configure babel

bash
yarn add --dev babel-plugin-emotion

.babelrc

json
{
  "plugins": [["emotion", { "extractStatic": true }]]
}

This js file, h1.js

jsx
import styled from 'react-emotion'

const H1 = styled('h1')`
  color: #ffd43b;
`

During babel compilation emotion will create h1.emotion.css and add import './h1.emotion.css' to the top of h1.js

css
/* h1.emotion.css */
.css-H1-duiy4a {
  color: blue;
}

h1.js after babel compilation

jsx
import './h1.emotion.css'
import styled from 'react-emotion'

const H1 = styled('h1', {
  e: 'css-duiy4a'
})()