Issue
I am trying to achieve something like the following output using styled components (shared selectors).
.styleOne, .styleTwo {
color: blue; /* shared */
}
.styleOne {
font-size: 10px;
}
.styleTwo {
font-size: 20px;
}
I've tried:
1 - (this one makes sense why it doesn't render my desired output)
const shared = `color: blue;`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
2 -
const Shared = styled.div`
color: blue;
`
const StyleOne = styled(Shared)`
font-size: 10px;
`
const StyleTwo = styled(Shared)`
font-size: 20px;
`
3 -
const shared = css`
color: blue;
`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
All the above result in something like the following:
.styleOne {
color: blue; /* duplicated */
font-size: 10px;
}
.styleTwo {
color: blue; /* duplicated */
font-size: 20px;
}
Technically the styles are shared in each approach from a code perspective. However, the rules are still duplicated. I was hoping to be able to share the CSS rules themselves.
An analogy in SASS would be - I want to use a placeholder instead of a mixin.
To add some context on why I want to achieve this, I want to have a smaller HTML document for performance reasons. I'm imagining in a large app where I'm sharing a lot of styles, the style block may get huge.
Solution
The term large apps is too ambiguous to state whether or not you'll have performance issues -- whether it's from downloading/executing JS or downloading parsing CSS and/or fetching other media (fonts, images, etc). That said, styled-components applies styles in the head
during run-time and does an excellent job of deferring them until they're required in the DOM.
Take a look at this example and follow these steps:
- Inspect the DOM and within the
Elements
tab expand thehead
- Look for this
style
tag and expand it:<style data-styled="active" data-styled-version="5.2.0"></style>
- With the inspector still open, navigate to other pages and notice how class names are generated on-the-fly
- Once the classes have been assigned, they're then reused
This has the similar effect of using css-modules (scoped classes) without the extra request to download the required CSS, and it automatically prefixes CSS properties without any additional plugins.
So the question becomes: Is it better to have more Javascript (packaging and running styled-components in run-time) and less CSS (less requests to download CSS per page) or more CSS and potentially less Javascript? You'll need to run metrics -- like a lighthouse test -- in production to determine which is more performant; otherwise, it's just going to be a guess/personal opinion.
Either way, you're going to be running into some sort of render blocking, whether it's downloading/parsing CSS or downloading/executing JS.
Answered By - Matt Carlotta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.