
Security News
ECMAScript 2025 Finalized with Iterator Helpers, Set Methods, RegExp.escape, and More
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
The 'uncss' npm package is a tool used to remove unused CSS from your stylesheets. It analyzes your HTML files to determine which CSS selectors are actually used and removes the unused ones, resulting in smaller and more efficient CSS files.
Remove Unused CSS
This feature allows you to remove unused CSS from your stylesheets by analyzing the HTML files you provide. The code sample demonstrates how to use the 'uncss' package to process a single HTML file and output the cleaned CSS.
const uncss = require('uncss');
const files = ['myPage.html'];
uncss(files, (error, output) => {
console.log(output);
});
Process Multiple Files
You can process multiple HTML files at once to remove unused CSS. This is useful for projects with multiple pages. The code sample shows how to pass an array of HTML files to 'uncss' and receive the cleaned CSS output.
const uncss = require('uncss');
const files = ['page1.html', 'page2.html'];
uncss(files, (error, output) => {
console.log(output);
});
Use with Options
The 'uncss' package allows you to specify options such as ignoring certain selectors or handling specific media queries. The code sample demonstrates how to use these options to customize the CSS cleaning process.
const uncss = require('uncss');
const files = ['index.html'];
const options = {
ignore: ['#ignored-id', '.ignored-class'],
media: ['(min-width: 700px) handheld and (orientation: landscape)']
};
uncss(files, options, (error, output) => {
console.log(output);
});
PurifyCSS is a tool similar to uncss that removes unused CSS. It scans your HTML and JavaScript files to determine which CSS selectors are used. Compared to uncss, PurifyCSS is known for its speed and ability to handle JavaScript-driven content more effectively.
PurgeCSS is another alternative to uncss that removes unused CSS. It is highly configurable and works well with modern build tools like Webpack and Gulp. PurgeCSS is often preferred for its flexibility and integration capabilities with various front-end workflows.
Clean-css is a fast and efficient CSS optimizer that can also remove unused CSS. While its primary focus is on minification and optimization, it can be used in conjunction with other tools to achieve similar results to uncss. It is known for its speed and comprehensive optimization features.
UnCSS is a tool that removes unused CSS from your stylesheets. It works across multiple files and supports Javascript-injected CSS.
The process by which UnCSS removes the unused rules is as follows:
document.querySelector
filters out selectors that are not found in the HTML files.Please note:
ignore
option to preserve classes that are added by Javascript on user interaction.npm install -g uncss
var uncss = require('uncss');
var files = ['my', 'array', 'of', 'HTML', 'files', 'or', 'http://urls.com'],
options = {
banner : false,
csspath : '../public/css/',
htmlroot : 'public',
ignore : ['#added_at_runtime', /test\-[0-9]+/],
ignoreSheets : [/fonts.googleapis/],
inject : function(window) { window.document.querySelector('html').classList.add('no-csscalc', 'csscalc'); },
jsdom : {
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
},
media : ['(min-width: 700px) handheld and (orientation: landscape)'],
raw : 'h1 { color: green }',
report : false,
strictSSL : true,
stylesheets : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css'],
timeout : 1000,
uncssrc : '.uncssrc',
userAgent : 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X)',
};
uncss(files, options, function (error, output) {
console.log(output);
});
/* Look Ma, no options! */
uncss(files, function (error, output) {
console.log(output);
});
/* Specifying raw HTML */
var rawHtml = '...';
uncss(rawHtml, options, function (error, output) {
console.log(output);
});
UnCSS can also be used in conjunction with other JavaScript build systems, such as Grunt, Broccoli or Gulp!
Usage: uncss [options] <file or URL, ...>
e.g. uncss https://getbootstrap.com/docs/3.3/examples/jumbotron/ > stylesheet.css
Options:
-h, --help output usage information
-V, --version output the version number
-i, --ignore <selector, ...> Do not remove given selectors
-m, --media <media_query, ...> Process additional media queries
-C, --csspath <path> Relative path where the CSS files are located
-s, --stylesheets <file, ...> Specify additional stylesheets to process
-S, --ignoreSheets <selector, ...> Do not include specified stylesheets
-r, --raw <string> Pass in a raw string of CSS
-t, --timeout <milliseconds> Wait for JS evaluation
-H, --htmlroot <folder> Absolute paths' root location
-u, --uncssrc <file> Load these options from <file>
-n, --noBanner Disable banner
-a, --userAgent <string> Use a custom user agent string
-I, --inject <file> Path to javascript file to be executed before uncss runs
-o, --output <file> Path to write resulting CSS to
Note that you can pass both local file paths (which are processed by glob) and URLs to the program.
banner (boolean, default: true
): Whether a banner should be prepended before each file block in the processed CSS.
csspath (string): Path where the CSS files are related to the HTML files. By default, UnCSS uses the path specified in the <link rel="stylesheet" href="path/to/file.css"/>
.
htmlroot (string): Where the project root is. Useful for example if you have HTML that references local files with root-relative URLs, i.e. href="/css/style.css"
.
ignore (string[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors:
/* uncss:ignore */
.selector1 {
/* this rule will be ignored */
}
.selector2 {
/* this will NOT be ignored */
}
/* uncss:ignore start */
/* all rules in here will be ignored */
/* uncss:ignore end */
ignoreSheets (string[] | RegExp[]): Do not process these stylesheets, e.g. Google fonts. Accepts strings or regex patterns.
inject (string / function(window)): Path to a local javascript file which is executed before uncss runs. A function can also be passed directly in.
Example inject.js file
'use strict';
module.exports = function(window) {
window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
};
Example of passing inject as a function
{
inject: function(window){
window.document.querySelector('html').classList.add('no-csscalc', 'csscalc');
}
}
jsdom (object) (Supported only by API): Supply the options used to create the JSDOM pages (https://github.com/jsdom/jsdom). At the moment, config.resources
is not yet supported.
media (string[]): By default UnCSS processes only stylesheets with media query _all_
, _screen_
, and those without one. Specify here which others to include.
raw (string): Give the task a raw string of CSS in addition to the existing stylesheet options; useful in scripting when your CSS hasn't yet been written to disk.
report (boolean, default: true
): Return the report object in callback.
strictSSL (boolean, default: true
): Disable SSL verification when retrieving html source
stylesheets (string[]): Use these stylesheets instead of those extracted from the HTML files. Prepend paths with the file://
protocol to force use of local stylesheets, otherwise paths will be resolved as a browser would for an anchor tag href
on the HTML page.
timeout (number): Specify how long to wait for the JS to be loaded.
uncssrc (string): Load all options from a JSON file. Regular expressions for the ignore
and ignoreSheets
options should be wrapped in quotation marks.
Example uncssrc file:
{
"ignore": [
".unused",
"/^#js/"
],
"stylesheets": [
"css/override.css"
]
}
userAgent (String, default: 'uncss'
): The user agent string that jsdom should send when requesting pages. May be useful when loading markup from services which use user agent based device detection to serve custom markup to mobile devices. Defaults to uncss
.
UnCSS can be used as a PostCSS Plugin.
postcss([ require('uncss').postcssPlugin ]);
See PostCSS docs for examples for your environment.
Note: Depending on your environment, you might not be able to use uncss as a PostCSS plugin since the plugin is not directly exported. In such cases, use the wrapper library postcss-uncss.
html (string[]): provide a list of html files to parse for selectors and elements. Usage of globs is allowed.
ignore (string[] | RegExp[]): provide a list of selectors that should not be removed by UnCSS. For example, styles added by user interaction with the page (hover, click), since those are not detectable by UnCSS yet. Both literal names and regex patterns are recognized. Otherwise, you can add a comment before specific selectors in your CSS:
/* uncss:ignore */
.selector1 {
/* this rule will be ignored */
}
.selector2 {
/* this will NOT be ignored */
}
{
html: ['index.html', 'about.html', 'team/*.html'],
ignore: ['.fade']
}
Copyright (c) 2019 Giacomo Martino. See the LICENSE file for license rights and limitations (MIT).
FAQs
Remove unused CSS styles
The npm package uncss receives a total of 167,983 weekly downloads. As such, uncss popularity was classified as popular.
We found that uncss demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
Security News
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.
Research
North Korean threat actors linked to the Contagious Interview campaign return with 35 new malicious npm packages using a stealthy multi-stage malware loader.