Quick Start

This guide provides a minimal "hello world" tutorial to get you started with UnCSS using both the CLI and the Node.js API.

Project Setup

First, let's create a simple project with an HTML file and a stylesheet.

  1. Create a new directory for your project:

    mkdir uncss-demo
    cd uncss-demo
  2. Create an index.html file:

    <!-- index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>UnCSS Demo</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h1 class="used-class">Hello, UnCSS!</h1>
    </body>
    </html>
  3. Create a style.css file with both used and unused styles:

    /* style.css */
    .used-class {
        color: blue;
    }
    
    .unused-class {
        color: red;
    }
    
    p {
        font-size: 16px;
    }

Using the CLI

If you've installed UnCSS globally, you can run it directly from your terminal.

  1. Run the uncss command, passing your HTML file as input and redirecting the output to a new CSS file.

    uncss index.html > cleaned.css
  2. Check the contents of cleaned.css:

    /* cleaned.css */
    .used-class {
        color: blue;
    }

As you can see, the .unused-class and p selectors were correctly identified as unused and removed.

Using the Programmatic API

If you want to integrate UnCSS into a script, you can use its Node.js API.

  1. First, install UnCSS locally in your project directory:

    npm init -y
    npm install uncss --save-dev
  2. Create a script named run-uncss.js:

    // run-uncss.js
    const uncss = require('uncss');
    const fs = require('fs');
    
    const files = ['index.html'];
    
    uncss(files, (error, output) => {
        if (error) {
            console.error('Error:', error);
            return;
        }
        console.log('--- Cleaned CSS ---');
        console.log(output);
    
        // Optionally, write the output to a file
        fs.writeFileSync('cleaned-api.css', output);
        console.log('\nSuccessfully wrote cleaned CSS to cleaned-api.css');
    });
  3. Run the script:

    node run-uncss.js
  4. You will see the cleaned CSS printed to your console and saved in cleaned-api.css:

    --- Cleaned CSS ---
    .used-class {
        color: blue;
    }
    
    Successfully wrote cleaned CSS to cleaned-api.css