vite-plugin-purgecss

raw JSON →
0.2.13 verified Mon Apr 27 auth: no javascript

A Vite plugin that removes unused CSS from the production build by integrating PurgeCSS. Version 0.2.13, actively maintained with occasional updates. Fork of vite-plugin-html-purgecss, it scans both HTML and JS output to find CSS class references, making it compatible with JavaScript frameworks like SvelteKit. Unlike PurgeCSS CLI, it works seamlessly within Vite's build pipeline without extra configuration. Lightweight and easy to set up, it accepts all standard PurgeCSS options including safelist for preserving dynamic classes. Supports TypeScript with bundled type definitions.

error Error: 'htmlPurge' is not defined
cause Using named import instead of default import.
fix
Use 'import htmlPurge from 'vite-plugin-purgecss''.
error TypeError: htmlPurge is not a function
cause Importing the package itself as a default export but it's actually a function.
fix
Ensure you are calling the default export as a function: htmlPurge({...}).
error Cannot find module 'vite-plugin-purgecss'
cause Package not installed or typo in import path.
fix
Run 'npm install vite-plugin-purgecss' and check the import path.
error Some CSS classes are missing in production build
cause PurgeCSS removed dynamic classes that were not in the scanned content.
fix
Add missing classes or patterns to the safelist option.
gotcha The plugin scans JS output for CSS strings, but does not detect dynamic style changes via JavaScript (e.g., element.style.color = 'red').
fix Add potentially dynamic classes to the safelist manually.
gotcha Plugin is a fork of 'vite-plugin-html-purgecss' and may have diverged in options or behavior.
fix Refer to this plugin's documentation rather than the original.
gotcha PurgeCSS removes unused CSS globally; may break styles for classes added by third-party libraries not present in your source code.
fix Use safelist or allow-duplication options to preserve expected classes.
npm install vite-plugin-purgecss
yarn add vite-plugin-purgecss
pnpm add vite-plugin-purgecss

Basic setup of vite-plugin-purgecss in Vite config with safelist option.

// vite.config.ts
import { defineConfig } from 'vite';
import htmlPurge from 'vite-plugin-purgecss';

export default defineConfig({
  plugins: [
    htmlPurge({
      content: ['./dist/**/*.html'],  // Adjust as needed
      safelist: ['keep-this-class'],  // Prevent removal of critical classes
      // Additional PurgeCSS options
    }),
  ],
});