react-boilerplate-cra-template
react-boilerplate-cra-template copied to clipboard
CSS with Media Queries are Not Minified (SOLUTION ATTACHED)
Issue: Babel-Plugin-Styled-Components Minification
Babel-Plugin-Styled-Components does not minify CSS in a few cases. I've fixed one of them by changing the media query utility to avoid template literals.
- Does not minify nested template literals (like those generated by the media queries utility)
FIXED
- Does not minify global styles
NEEDS FIX
- Does not minify keyframes
NEEDS FIX
This is a known issue, but can be worked around with some changes.
Example
Styled-Components CSS
${media.medium` color: white; background-color: white; content: 'helloooo'; div { color: red; border: 1px solid red; border-radius: 5px; padding: 5px; &:hover { background-color: red; color: white; } } a { color: blue; border: 1px solid blue; border-radius: 5px; padding: 5px; } `}
Compiled Bundle Before (424 bytes)
k.medium(P||(P=(0,a.Z)(["\n color: white;\n background-color: white;\n content: 'helloooo';\n div {\n color: red;\n border: 1px solid red;\n border-radius: 5px;\n padding: 5px;\n\n &:hover {\n background-color: red;\n color: white;\n }\n }\n\n a {\n color: blue;\n border: 1px solid blue;\n border-radius: 5px;\n padding: 5px;\n }\n "])))
Compiled Bundle After (281 bytes)
"{color:white;background-color:white;content:'helloooo';div{color:red;border:1px solid red;border-radius:5px;padding:5px;&:hover{background-color:red;color:white;}}a{color:blue;border:1px solid blue;border-radius:5px;padding:5px;}}"],"@media (min-width: ".concat(R["medium"],"px)")
Solution
To solve this, I've created a new media query utility function, with a slightly changed syntax (a little easier to read, I think)
Change ${media.medium` color: white; `}
to ${media.medium} { color: white; }
Benefits
- Allows CSS to be minified like it's supposed to be, making bundle sizes smaller for all projects with media queries
- Easier to use for developers. Nested template literals are harder to read.
See fix here
Notes
This is technically a breaking change, just like the recent switch from React Router v5 to v6. To avoid requiring code changes, the new media function could simply live beside the old one, rather than replacing it.