PurgeCSS

This guide covers vite-plugin-tailwind-purgecss, a simple Vite plugin that thoroughly purges excess CSS via PurgeCSS. While optional, this is highly recommended if you wish to minimize your production CSS bundle size.

View on GitHub

Introduction

Motivation

Tailwind UI component libraries like Skeleton and Flowbite provide a number of benefits, but come with an important caveat - Tailwind generates classes for all imported components, regardless if they are used in the project or not. This leads to a larger than necessary CSS bundle.

Unfortunately this is a limitation of how Tailwind implements it's Content Configuration. Tailwind searches through all files specified in content, uses a regex to locate possible selectors, then generates their respective classes. The key thing to note is this occurs before the build process, meaning there's no CSS treeshaking or purging involved against your production file assets.

How it Works

Ideally, we would like to limit selectors to only those used within your project. We accomplish this by analyzing the emitted Javascript chunks generated by Rollup, which includes only the modules that are actually used in your project, then it extracts the utilized selectors. From there, we can pass along the selectors to PurgeCSS for final processing.


Usage

Installation

terminal
npm i -D vite-plugin-tailwind-purgecss

Add to Vite

Implement the following in vite.config.ts, found in the root of your project.

typescript
import { purgeCss } from 'vite-plugin-tailwind-purgecss';

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

Safelisting

To denote selectors that shouldn't be purged, simply add them via safelist in your vite.config.ts.

typescript
import { purgeCss } from 'vite-plugin-tailwind-purgecss';

const config: UserConfig = {
	plugins: [
		sveltekit(),
		purgeCss({
			safelist: {
				// any selectors that begin with "hljs-" will not be purged
				greedy: [/^hljs-/],
			},
		}),
	],
};

Alternatively, can safelist selectors directly within your stylesheets using special comments.

css
/*! purgecss start ignore */

h1 {
	color: red;
}

h2 {
	color: blue;
}

/*! purgecss end ignore */

You may also safelist selectors directly within each declaration block.

css
h3 {
	/*! purgecss ignore current */
	color: pink;
}

See the PurgeCSS documentation for additional configuration settings.


Attribution

This plugin is provided courtesy of Skeleton co-maintainer Adrian (aka CokaKoala).