PurgeCSS

repository·main·Indexed 11 days ago

https://github.com/FullHuman/purgecss

A CSS optimizer that analyzes content files to identify used selectors and removes unused CSS from stylesheets to reduce file size. It provides a JavaScript API, a CLI, and plugins for build tools including PostCSS (@fullhuman/postcss-purgecss), Webpack (purgecss-webpack-plugin), Gulp (gulp-purgecss), and Grunt (grunt-purgecss). It supports custom extractors, safelisting, and the removal of unused keyframes and @font-face rules.

Tokens
34.9K
Snippets
135
Records
166
Agent score
88%

What's inside PurgeCSS

  1. What is PurgeCSS?

    main

    PurgeCSS is a tool designed to remove unused CSS from your project, helping to reduce file size and improve performance. It is designed to be integrated into existing development workflows and provides multiple ways to interact with it:

    • JavaScript API: For programmatic control within your own scripts.
    • CLI: For running PurgeCSS directly from the terminal.
    • Plugins: Dedicated integrations for popular build tools and frameworks (e.g., PostCSS, Webpack, Gulp, Grunt, Gatsby, Vue, React, etc.).
  2. Ways to use PurgeCSS

    main

    PurgeCSS can be integrated into your development workflow using several different interfaces:

    • JavaScript API: For programmatic control within your own scripts.
    • CLI: For running PurgeCSS directly from your terminal.
    • Build Tool Plugins: For seamless integration with popular bundlers and task runners (e.g., PostCSS, Webpack, Gulp, Grunt, Rollup, and Vue CLI).
  3. What is PurgeCSS?

    main
    PurgeCSS is a tool used to reduce the size of CSS files by analyzing your content files (HTML, JS, etc.) and matching the selectors used against your CSS files. It identifies and removes unused CSS selectors, which is particularly useful when using large CSS frameworks like Bootstrap, Materializecss, or Foundation where only a small subset of styles is actually utilized.
  4. What is PurgeCSS and how does it work?

    main

    PurgeCSS is a tool designed to remove unused CSS from your project to reduce file size. It is particularly useful when using large CSS frameworks like TailwindCSS, Bootstrap, MaterializeCSS, or Foundation, where only a small subset of the styles is actually utilized in your application.

    How it works:

    1. Analysis: PurgeCSS analyzes your content files (e.g., HTML, JavaScript, templates) and your CSS files.
    2. Matching: It matches the selectors found in your content files against the selectors defined in your CSS.
    3. Purging: It removes any CSS selectors that do not have a corresponding match in your content files, resulting in a significantly smaller CSS output.
  5. Available PurgeCSS Integration Methods

    main

    PurgeCSS can be used through several interfaces depending on your project setup:

    Core Interfaces

    • Configuration: Define how PurgeCSS behaves.
    • Command Line Interface (CLI): Run via terminal commands.
    • Programmatic API: Use as a library in JavaScript code.
    • Safelisting: Protect specific CSS selectors from being purged.
    • Extractors: Define custom logic for identifying used classes.

    Build Tool Plugins

    • PostCSS: @fullhuman/postcss-purgecss
    • Webpack: purgecss-webpack-plugin
    • Gulp: gulp-purgecss
    • Grunt: grunt-purgecss
    • Gatsby: Gatsby-specific integration

    Framework Guides

    PurgeCSS provides specific guidance for integrating with:

    • Vue.js and Nuxt.js
    • React.js and Next.js
    • Razzle
    • WordPress
    • Hugo
  6. Important considerations for Gatsby PurgeCSS

    main

    When using gatsby-plugin-purgecss, keep the following in mind:

    • Risk of removing required styles: This is not an 'install and forget' plugin. It may remove required styles by default if they aren't explicitly detected in your content files.
    • Selector Matching: Selector matching is case-sensitive; my-selector will not match mySelector.
    • Scanning Scope: Only files processed by Webpack will be purged. By default, only js, jsx, ts, tsx files are scanned for selectors. To include .md or .mdx files, you must configure the content option:
      content: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}')]
    • Best Practice: Instead of complex content configurations, it is often safer to use the whitelist option to protect required selectors.
  7. Compare PurgeCSS with PurifyCSS

    main

    The primary difference between PurgeCSS and PurifyCSS lies in how they identify used selectors:

    • PurifyCSS uses a 'word-matching' approach, treating every word in your files as a potential selector. This lack of modularity can lead to false positives, where a word in a text paragraph accidentally matches a CSS selector, preventing it from being purged.
    • PurgeCSS solves this via Extractors. An extractor is a function that takes file content and returns a specific list of CSS selectors. This allows you to use parsers that return an AST (Abstract Syntax Tree) to find selectors precisely, ensuring that only actual CSS selectors are matched and unused styles are correctly removed.
  8. Compare PurgeCSS with UnCSS

    main

    When deciding between PurgeCSS and UnCSS, consider your project's architecture and rendering method:

    • UnCSS uses jsdom to emulate a browser environment and execute JavaScript. This makes it highly accurate for simple websites with HTML and JavaScript, as it can identify selectors generated at runtime. However, it has higher performance costs and requires converting templates (like Pug) to HTML before processing.
    • PurgeCSS uses a modular extractor system. Instead of full browser emulation, you can use specific extractors for frameworks (Vue, React, Aurelia) or file types (pug, ejs). This approach aims to provide high accuracy and better CSS size results without the overhead of jsdom emulation.
  9. How purgecss-from-html works

    main

    The extractor uses the parse5 library to parse HTML into an Abstract Syntax Tree (AST). It then traverses the tree to extract:

    1. Tag names: All HTML elements (e.g., div, span, button).
    2. Classes: Values from class attributes, split by spaces.
    3. IDs: Values from id attributes.
    4. Attributes: Both attribute names and values, which enables support for attribute selectors like [data-theme] or [class*=foo].
  10. How @fullhuman/purgecss-from-tsx works

    main

    The extractor operates in a two-step pipeline:

    1. TypeScript Transpilation: Uses the TypeScript compiler to transpile TSX into JSX. This process strips type annotations while ensuring JSX syntax is preserved.
    2. JSX Extraction: Uses @fullhuman/purgecss-from-jsx to parse the resulting JSX and extract the relevant selectors.

    What it extracts

    • Component names: JSX element names (e.g., div, Header, MyComponent).
    • className values: String values from className attributes, split by spaces.
    • id values: String values from id attributes.
  11. How PurgeCSS Extractors work

    main

    An extractor is a core PurgeCSS mechanism used to improve accuracy and prevent false positives.

    Instead of blindly matching words (like PurifyCSS), an extractor is a function that processes file content to extract a list of valid CSS selectors. This can be implemented in several ways:

    • Default Extractor: A general-purpose extractor provided by PurgeCSS.
    • AST-based Extractors: Using a parser to generate an Abstract Syntax Tree (AST) and traversing it to find selectors (e.g., how purgecss-from-html operates).
    • Custom Extractors: Developers can write custom extractors for specific frameworks (Vue, React, etc.) or template engines (Pug, EJS) to ensure the most accurate removal of unused CSS.
  12. What selectors are extracted from JSX

    main

    The extractor parses JSX and identifies the following types of selectors:

    1. Component names: JSX element names (e.g., div, Header, MyComponent).
    2. className values: String values from className attributes, split by spaces.
    3. id values: String values from id attributes.

    Example Input:

    <Card className="card card-primary" id="featured-card">
      <CardHeader />
      <CardBody className="p-4" />
    </Card>

    Extracted Selectors: ["Card", "card", "card-primary", "featured-card", "CardHeader", "CardBody", "p-4"]