vite-plugin-svelte-purgecss
v0.2.7
Published
Vite plugin for PurgeCSS for Svelte
Downloads
1,088
Maintainers
Readme
Notice!
This package has been moved to vite-plugin-tailwind-purge as the internals have been refactored to be more generalized. Worry not though, Svelte will still be properly supported!
vite-plugin-svelte-purgecss
A simple vite plugin that thoroughly purges excess CSS from Svelte projects using PurgeCSS. This package should be used in combination with Tailwind and a Tailwind specific UI library such as Skeleton.
Motivation
PurgeCSS is an excellent package that removes unused CSS. Their provided plugins for extraction do a decent enough job for simple projects. However, plugins such as postcss-purgecss and rollup-plugin-purgecss take a rather naive approach to selector extraction. They only analyze the content that is passed to them through their content
fields, which means that if you pass a UI library to it, none of the selectors that are unused in your project (such as components that aren't imported) will be properly purged. Leaving you with a larger than necessary CSS bundle.
Ideally, we'd like to keep the selectors that are only used in your project. We accomplish by analyzing the emitted JS chunks that are generated by Rollup, and extracting out any of their possible selectors. From there, we can pass along the selectors to PurgeCSS for final processing.
⚠ Caveats ⚠
This package is still very experimental. Breaking changes can occur at any time. We'll stabilize once we hit a 1.0.0
release.
Usage
Installation
npm i -D vite-plugin-svelte-purgecss
Add to Vite
// vite.config.ts
import { purgeCss } from 'vite-plugin-svelte-purgecss';
const config: UserConfig = {
plugins: [sveltekit(), purgeCss()],
};
Safelisting
If selectors that shouldn't be purged are being removed, simply add them to the safelist
.
// vite.config.ts
import { purgeCss } from 'vite-plugin-svelte-purgecss';
const config: UserConfig = {
plugins: [
sveltekit(),
purgeCss({
safelist: {
// any selectors that begin with "hljs-" will not be purged
greedy: [/^hljs-/],
},
}),
],
};
Alternatively, if you'd like to safelist selectors directly in your stylesheets, you can do so by adding special comments:
/*! purgecss start ignore */
h1 {
color: red;
}
h2 {
color: blue;
}
/*! purgecss end ignore */
You can also safelist selectors directly in the declaration block as well:
h3 {
/*! purgecss ignore current */
color: pink;
}
For further configuration, you can learn more here.