PurgeCSS

This guide covers vite-plugin-tailwind-purgecss, a simple Vite plugin that purges excess TailwindCSS styles 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 files that are part of your project's module graph, then it extracts the utilized tailwindcss classes. 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()],
};

Attribution

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