Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I opt for React Styled-Components to generate a physical CSS file?

I need the CSS that is provided to styled-components to be output to a physical CSS file inside of my public/css directory.

export const MyComp = styled.div`
  width: 100%;
  height: 500px;
`

Along with styles from all other styled-components, the above component would output into public/css/styled.css:

.Components_MyComp__a39t9ag0248f {
  width: 100%;
  height: 500px;
}

I am using:

"webpack": "^2.6.1",
"styled-components": "^2.0.1",
like image 537
Colton Colcleasure Avatar asked Jul 05 '17 03:07

Colton Colcleasure


People also ask

Does styled-components generate CSS?

Existing CSSstyled-components generates an actual stylesheet with classes, and attaches those classes to the DOM nodes of styled components via the className prop. It injects the generated stylesheet at the end of the head of the document during runtime.

Where do you keep styled-components in React?

Structuring in styled-components can take different forms, you can decide to keep all styled components in the same file as the component that uses it - just like in React Native. Or you could have all the styled components of a page in a separate file and import them as needed.


1 Answers

This is currently not possible/supported. Doing extraction of static styles is very hard, for example consider a function interpolation:

const Test = styled.div`
  color: ${props => props.color};
`

How are we going to extract this? We could only extract the static parts of the CSS, but there's a lot of edge cases and constraints that make this hard to build.

We're currently investigating and experimenting to figure out what the best approach might be. For now check out our Babel plugin to see some things were working on at the compile time step!

like image 106
mxstbr Avatar answered Oct 14 '22 04:10

mxstbr