Programmatic Usage (Node.js API)

UnCSS can be used directly within your Node.js applications and build scripts. This allows for powerful automation and integration.

Basic Usage

To use UnCSS programmatically, you first need to require the module.

const uncss = require('uncss');

The main uncss function accepts an array of files or URLs, an optional options object, and a callback function.

Function Signature

uncss(files, [options], callback)
  • files (Array | String): An array of HTML file paths, URLs, or raw HTML strings to process.
  • options (Object, optional): A configuration object. See the Configuration page for a full list of options.
  • callback (Function): A function to be executed upon completion. It receives two arguments: error and output.

Example with Callback

Here is a complete example demonstrating how to use the API with a callback:

const uncss = require('uncss');

const myHtmlFiles = ['index.html', 'about.html'];

const options = {
    ignore: ['#dynamic-id', /.js-.*/],
    stylesheets: ['/css/main.css'],
    timeout: 1000
};

uncss(myHtmlFiles, options, (error, output) => {
    if (error) {
        console.error('An error occurred:', error);
        return;
    }

    console.log('UnCSS processed the files successfully!');
    console.log(output); // The cleaned CSS
});

Promise-Based Usage

If you prefer using Promises (or async/await), you can omit the callback function. UnCSS will return a Promise that resolves with an object containing the css and report.

const uncss = require('uncss');

const myHtmlFiles = ['index.html', 'about.html'];

const options = {
    report: true // Enable report generation
};

async function runUncss() {
    try {
        const { css, report } = await uncss(myHtmlFiles, options);
        console.log('Cleaned CSS:', css);
        console.log('Report:', report);
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

runUncss();

Processing Raw HTML

You can also pass a raw HTML string directly to UnCSS instead of file paths.

const rawHtml = `
    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" href="./style.css">
    </head>
    <body>
        <div class="used">Hello</div>
    </body>
    </html>
`;

uncss(rawHtml, { raw: '.used { color: blue; } .unused { color: red; }' }, (error, output) => {
    console.log(output);
    // .used { color: blue; }
});