Usage with PostCSS

UnCSS can be seamlessly integrated into your build process as a PostCSS plugin. This is a powerful way to automate CSS optimization.

Basic Setup

To use UnCSS with PostCSS, add uncss.postcssPlugin to your PostCSS configuration.

Here is an example postcss.config.js file:

// postcss.config.js
const uncss = require('uncss');

module.exports = {
  plugins: [
    uncss.postcssPlugin({
      html: ['index.html', 'about.html', 'team/*.html'],
      ignore: ['.fade']
    }),
    // ... other PostCSS plugins
  ]
};

When you run PostCSS, it will process your CSS, and the UnCSS plugin will strip out any rules that are not found in the provided HTML files.

Plugin-Specific Options

When used as a PostCSS plugin, UnCSS accepts a specific set of options:

  • html (Array of strings, required): An array of HTML file paths to scan for selectors. Glob patterns are supported.
  • ignore (Array of strings or RegExps, optional): A list of selectors to explicitly keep in the final output, even if they are not found in the HTML.

All other standard UnCSS options can also be passed here. See the Configuration Reference for a full list.

Example Configuration

{
  html: ['src/views/**/*.html'],
  ignore: [/^\.js-/, '.is-active']
}

Important Notes

  • The PostCSS plugin processes the CSS that is passed to it in the PostCSS stream. It ignores any <link> tags in your HTML files by default.
  • Depending on your build environment, you might encounter issues directly importing uncss.postcssPlugin. If you do, consider using the dedicated wrapper library postcss-uncss, which is designed for easier integration.