Discard duplicate rules in your CSS files with PostCSS.
npx @tessl/cli install tessl/npm-postcss-discard-duplicates@6.0.0PostCSS Discard Duplicates is a PostCSS plugin that removes duplicate rules, declarations, and at-rules from CSS stylesheets to optimize file size. It provides intelligent deduplication by comparing node types, selectors, properties, values, and importance flags while preserving the semantic structure of CSS.
npm install postcss-discard-duplicatesconst postcssDiscardDuplicates = require("postcss-discard-duplicates");For ES modules (using TypeScript-style import):
import postcssDiscardDuplicates = require("postcss-discard-duplicates");Or with modern ES module syntax:
import postcssDiscardDuplicates from "postcss-discard-duplicates";const postcss = require("postcss");
const postcssDiscardDuplicates = require("postcss-discard-duplicates");
// Using PostCSS directly
const result = await postcss([
postcssDiscardDuplicates()
])
.process(css, { from: "input.css", to: "output.css" });
console.log(result.css);Example transformation:
Input CSS:
h1 {
margin: 0 auto;
margin: 0 auto
}
h1 {
margin: 0 auto
}Output CSS:
h1 {
margin: 0 auto
}Creates a PostCSS plugin instance that removes duplicate CSS constructs.
/**
* Creates a PostCSS plugin that removes duplicate rules, declarations, and at-rules
* @returns {import('postcss').Plugin} PostCSS plugin object
*/
function postcssDiscardDuplicates(): import('postcss').Plugin;The plugin works by:
/**
* PostCSS plugin compatibility flag
*/
postcssDiscardDuplicates.postcss: true;interface Plugin {
postcssPlugin: string;
OnceExit(root: import('postcss').Root): void;
}The plugin removes duplicates based on exact matching:
The plugin does not normalize:
h1, h2 vs h2, h1 are considered different)margin: 10px 0 10px 0 vs margin: 10px 0)The plugin operates on the PostCSS AST and does not throw exceptions during normal operation. Invalid CSS should be handled by PostCSS parsing before the plugin runs.
The plugin uses efficient node comparison algorithms and processes the CSS tree recursively. Performance scales with the number of duplicate constructs rather than total CSS size.