react-boilerplate / react-boilerplate-cra-template

:fire: Setup Create React App with React Boilerplate. Highly scalable & Best DX & Performance Focused & Best practices.
https://react-boilerplate.github.io/react-boilerplate-cra-template/
MIT License
1.87k stars 392 forks source link

CSS with Media Queries are Not Minified (SOLUTION ATTACHED) #199

Closed qeleb closed 1 year ago

qeleb commented 1 year ago

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.

  1. Does not minify nested template literals (like those generated by the media queries utility) FIXED
  2. Does not minify global styles NEEDS FIX
  3. 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
  1. Allows CSS to be minified like it's supposed to be, making bundle sizes smaller for all projects with media queries
  2. 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.

Can-Sahin commented 1 year ago

@qeleb should I close this since I merged it the PR. Was that it?

qeleb commented 1 year ago

yes this is good to close. Also, I’ve since found a better way to minify the template literal css. If i configure it then either way will work so it’s just up to syntax preference