optimise for ternary expressions when excluding unused css (#696)

pull/734/head
Rich Harris 7 years ago
parent 608f8943f3
commit 4daa57c67b

@ -1,4 +1,5 @@
import MagicString from 'magic-string';
import { gatherPossibleValues, UNKNOWN } from './gatherPossibleValues';
import { Validator } from '../validate/index';
import { Node } from '../interfaces';
@ -192,12 +193,22 @@ function attributeMatches(node: Node, name: string, expectedValue: string, opera
const attr = node.attributes.find((attr: Node) => attr.name === name);
if (!attr) return false;
if (attr.value === true) return operator === null;
if (isDynamic(attr.value)) return true;
const actualValue = attr.value[0].data;
if (attr.value.length > 1) return true;
const pattern = operators[operator](expectedValue, caseInsensitive ? 'i' : '');
return pattern.test(actualValue);
const value = attr.value[0];
if (value.type === 'Text') return pattern.test(value.data);
const possibleValues = new Set();
gatherPossibleValues(value.expression, possibleValues);
if (possibleValues.has(UNKNOWN)) return true;
for (const x of Array.from(possibleValues)) { // TypeScript for-of is slightly unlike JS
if (pattern.test(x)) return true;
}
return false;
}
function isDynamic(value: Node) {

@ -0,0 +1,18 @@
import { Node } from '../interfaces';
export const UNKNOWN = {};
export function gatherPossibleValues(node: Node, set: Set<string|{}>) {
if (node.type === 'Literal') {
set.add(node.value);
}
else if (node.type === 'ConditionalExpression') {
gatherPossibleValues(node.consequent, set);
gatherPossibleValues(node.alternate, set);
}
else {
set.add(UNKNOWN);
}
}

@ -13,7 +13,7 @@ function tryRequire(file) {
}
function normalizeWarning(warning) {
warning.frame = warning.frame.replace(/^\n/, '').replace(/^\t+/gm, '');
warning.frame = warning.frame.replace(/^\n/, '').replace(/^\t+/gm, '').replace(/\s+$/gm, '');
delete warning.filename;
delete warning.toString;
return warning;

@ -0,0 +1,24 @@
export default {
cascade: false,
data: {
active: true
},
warnings: [{
filename: "SvelteComponent.html",
message: "Unused CSS selector",
loc: {
line: 12,
column: 1
},
pos: 125,
frame: `
10: }
11:
12: .maybeactive {
^
13: color: green;
14: }`
}]
};

@ -0,0 +1 @@
.active[svelte-xyz]{color:red}.inactive[svelte-xyz]{color:blue}

@ -0,0 +1 @@
<div svelte-xyz="" class="active"></div>

@ -0,0 +1,15 @@
<div class='{{active ? "active": "inactive"}}'></div>
<style>
.active {
color: red;
}
.inactive {
color: blue;
}
.maybeactive {
color: green;
}
</style>

@ -1,10 +0,0 @@
[{
"filename": "SvelteComponent.html",
"message": "Unused CSS selector",
"loc": {
"line": 8,
"column": 1
},
"pos": 61,
"frame": " 6: }\n 7: \n 8: .bar {\n ^\n 9: color: blue;\n10: }"
}]
Loading…
Cancel
Save