Skip to content

Commit

Permalink
fix: css variable removed when declared in wrong order
Browse files Browse the repository at this point in the history
  • Loading branch information
Ffloriel committed Mar 21, 2021
1 parent 2f9cc65 commit 89ece42
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
5 changes: 4 additions & 1 deletion packages/purgecss/__tests__/css-variables.test.ts
@@ -1,5 +1,4 @@
import PurgeCSS from "./../src/index";

import { ROOT_TEST_EXAMPLES } from "./utils";

describe("purge unused css variables", () => {
Expand All @@ -25,4 +24,8 @@ describe("purge unused css variables", () => {
expect(purgedCSS.includes("--unused-color")).toBe(false);
expect(purgedCSS.includes("--button-color")).toBe(false);
});
it("keeps '--color-first:', '--wrong-order'", () => {
expect(purgedCSS.includes("--color-first:")).toBe(true);
expect(purgedCSS.includes("--wrong-order:")).toBe(true);
});
});
@@ -1,10 +1,13 @@
:root {
--color-first: var(--wrong-order);
--primary-color: blue;
--secondary-color: indigo;
--tertiary-color: aqua;
--unused-color: violet;
--used-color: rebeccapurple;
--accent-color: orange;
--wrong-order: yellow;
--random: var(--not-existing);
}

.button {
Expand All @@ -19,4 +22,5 @@
.button:focus {
background-color: var(--accent-color);
color: var(--primary-color);
border-color: var(--color-first);
}
18 changes: 18 additions & 0 deletions packages/purgecss/src/VariablesStructure.ts
@@ -1,4 +1,5 @@
import * as postcss from "postcss";
import { matchAll } from "./index";
import { StringRegExpArray } from "./types";

class VariableNode {
Expand Down Expand Up @@ -62,9 +63,26 @@ class VariablesStructure {
}

removeUnused(): void {
// check unordered usage
for (const used of this.usedVariables) {
const usedNode = this.nodes.get(used);
if (usedNode) {
const usedVariablesMatchesInDeclaration = matchAll(
usedNode.value.value,
/var\((.+?)[,)]/g
);
usedVariablesMatchesInDeclaration.forEach((usage) => {
if (!this.usedVariables.has(usage[1])) {
this.usedVariables.add(usage[1]);
}
});
}
}

for (const used of this.usedVariables) {
this.setAsUsed(used);
}

for (const [name, declaration] of this.nodes) {
if (!declaration.isUsed && !this.isVariablesSafelisted(name)) {
declaration.value.remove();
Expand Down
2 changes: 1 addition & 1 deletion packages/purgecss/src/index.ts
Expand Up @@ -243,7 +243,7 @@ function isInPseudoClass(selector: selectorParser.Node): boolean {
);
}

function matchAll(str: string, regexp: RegExp): RegExpMatchArray[] {
export function matchAll(str: string, regexp: RegExp): RegExpMatchArray[] {
const matches: RegExpMatchArray[] = [];
str.replace(regexp, function () {
// eslint-disable-next-line prefer-rest-params
Expand Down

0 comments on commit 89ece42

Please sign in to comment.