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.
-
Create a new directory for your project:
mkdir uncss-demo cd uncss-demo
-
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>
-
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.
-
Run the
uncss
command, passing your HTML file as input and redirecting the output to a new CSS file.uncss index.html > cleaned.css
-
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.
-
First, install UnCSS locally in your project directory:
npm init -y npm install uncss --save-dev
-
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'); });
-
Run the script:
node run-uncss.js
-
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