Optimize, reduce CSS size on SvelteKit

Davgatseren
Dev notes from teo
Published in
2 min readFeb 28, 2023

I’ve built my portfolio website with SvelteKit, Carbon Components Svelte and Tailwind CSS. It was a great developer experience. But the site was so slow because CSS loading time was taking around 2 seconds on a first-time visit to the website.

File sizes before optimization are shown in the image.

File sizes before optimization

As you can see _layout.cc730ff2.css file size is 718.37 kB. So I tried to optimize and reduce the CSS bundle size. Carbon Components Svelte has a supporting library called Carbon preprocess svelte. This library can do the following things.

  • Optimize imports
  • Optimize CSS
  • Optimize icons and many more

In this case, I am gonna use Optimize CSS feature. To do that, you need to add the carbon-preprocess-svelte optimizeCSS feature in vite.config.js.

import { sveltekit } from '@sveltejs/kit/vite';
import { optimizeCss } from 'carbon-preprocess-svelte';

const config = {
plugins: [sveltekit(), optimizeCss({})]
};

export default config;

As you can see _layout.cc730ff2.css file size was reduced by 602.05 kB.
After first optimizing the build:

This is awesome, but I have faced another issue. Tailwind CSS some styles were purged and the site design had been broken. To fix this issue I specified a safelist for optimizing CSS functions.

import { sveltekit } from '@sveltejs/kit/vite';
import { optimizeCss } from 'carbon-preprocess-svelte';

const config = {
plugins: [
sveltekit(),
optimizeCss({
safelist: {
// TODO: need improvement on regex
// standard: [/[A-Za-z0-9-_:\/]+/g]
standard: [
/sm/g,
/md/g,
/lg/g,
/xl/g,
/2xl/g,
/auto/g,
/py/g,
/hidden/g,
/m/g,
/p/g,
/py/g,
/[A-Za-z0-9]\\:/g,
/h-[0-9\\.]/g
]
}
})
],
};

export default config;

After the final optimization of the build:

The first CSS file size was 718.37 kB then now it’s 334.36 kB. CSS file size is almost reduced by 53% and load time is faster on the first visit to the website.
I think it is awesome.

--

--