Skip to content

Commit 17d5a88

Browse files
committed
keep(sel) -> shouldDrop(sel) & show logging of removed selectors
1 parent 774a15a commit 17d5a88

File tree

3 files changed

+21
-8
lines changed

3 files changed

+21
-8
lines changed

README.md

+16-5
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ The entire logic for DropCSS is this [~60 line file](https://github.com/leeoniya
1717
### Install
1818

1919
```
20-
npm install --save-dev dropcss
20+
npm install -D dropcss
2121
```
2222

2323
---
@@ -45,17 +45,28 @@ let css = `
4545
}
4646
`;
4747

48+
const whitelist = /\b(?:#foo|\.bar)\b/;
49+
50+
let dropped = new Set();
51+
4852
let cleansedCSS = dropcss({
4953
html,
5054
css,
51-
keep: (sel) => {
52-
// test selector against some whitelist
53-
// and return `true` to retain it
54-
return /#foo/.test(sel);
55+
shouldDrop: (sel) => {
56+
if (whitelist.test(sel))
57+
return false;
58+
else {
59+
dropped.add(sel);
60+
return true;
61+
}
5562
},
5663
})
5764
```
5865

66+
`shouldDrop` is called for every CSS selector that could not be matched in the `html`.
67+
Return `false` to retain it or `true` to drop it.
68+
Additionally, this callback can be used to log all removed selectors.
69+
5970
---
6071
### Features
6172

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "dropcss",
3-
"version": "0.1.0",
3+
"version": "0.2.0",
44
"description": "Unused CSS Cleaner",
55
"main": "./src/dropcss.js",
66
"scripts": {

src/dropcss.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ const adapter = require("./adapter");
66
// https://developer.mozilla.org/en-US/docs/Web/CSS/pseudo-classes
77
const pseudoClassNonTransient = /:(?:first|last|nth|only|not|empty)\b/; // |lang
88

9+
const doDrop = sel => true;
10+
911
function dropcss(opts) {
1012
const htmlAst = parse(opts.html);
1113

@@ -15,7 +17,7 @@ function dropcss(opts) {
1517
parseAtrulePrelude: false
1618
});
1719

18-
const keep = opts.keep || (() => false);
20+
const shouldDrop = opts.shouldDrop || doDrop;
1921

2022
csstree.walk(cssAst, function(node, item, list) {
2123
if (node.type == "Rule") {
@@ -33,7 +35,7 @@ function dropcss(opts) {
3335
// remove any empty leftovers eg :not() - [tabindex="-1"]:focus:not(:focus-visible)
3436
.replace(/:[a-z-]+\(\)/gm, '');
3537

36-
if (domSel == '' || CSSselect.selectOne(domSel, htmlAst.childNodes, {adapter}) || keep(sel))
38+
if (domSel == '' || CSSselect.selectOne(domSel, htmlAst.childNodes, {adapter}) || shouldDrop(sel) !== true)
3739
pre.push(sel);
3840
});
3941

0 commit comments

Comments
 (0)