Here, several approaches will be introduced to reduce your front-end code base, especially, for reducing css codes.
Tailwind
- Link: tailwindcss
tailwindcss
provides fast, flexible, reliable css classes. Using tailwind
you can save time writing your css codes.
For instance, truncate
for:
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
To optimize css codes in production
- Refer to cssnano and Brotli as mentioned in tailwind docs
css-checker
- Link: css-checker
Wonder how to find your duplicated css codes? There is a automatic tool that can help you scanning all your css & styled-components codes and show similar classes with diffs.
- To Install:
npm install -g css-checker-kit
- To Run:
css-checker
Using useSWR
Link: useSWR
useSWR
can help you to reduce parsing states between components, just calluseSWR
in anywhere you wish to use the states.useSWR
can also help you to reduce duplicated requests and auto-fetch after users' re-focus.
The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
- To use it, it's quite simple:
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
Top comments (5)
As you're mentioning Tailwind its probably almost import to mention their official documentation. tailwindcss.com/docs/optimizing-fo... mentions cssnano or Brotli to further optimize the size of the code sent to the client.
However this all depends on the build steps you already have for prod.
Thanks for mentioning cssnano and Brotli. They are now mentioned inside the doc above.
What about styled components?
I find it more useful (maintainability, reusability...) than Tailwind which messes up the html/jsx.
styled-components is a good approach to struct styling codes. But yet, it's priority is not to reduce the size of code base.
Styles are declarative so there's no way to reduce the code base (even if you add an UI kit, the code will be in this kit and thus will be loaded and interpreted).
It's like pretending to reduce HTML code, it makes a non sense, ehat you will do is to optimise as best as possible and reduce unused code to the minimum.