Unused variable is not detected
Khazl opened this issue · comments
If you have a variable which name is a part of an other variable, it's flagged as used. It is because the ReExp find more than one occurrence.
const variables = ['$unused', '$black', '$black-light', '$black-lightest'];
const sassFilesString = '$unused: #123; $black: #000; $black-light: #111; $black-lightest: #222; .class {color: $black;}';
function regExpQuote(str) {
return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&');
}
const unusedVars = variables.filter(variable => {
const re = new RegExp(regExpQuote(variable), 'g');
return sassFilesString.match(re).length === 1;
});
console.log(unusedVars); // ["$unused", "$black-lightest"]
$black
and $black-light
are not used in the SCSS code but part of $black-lightest
Oh, and add a test case in the dummy test suite we have
Confirmed that this is a bug, pushed a few more tests https://github.com/XhmikosR/find-unused-sass-variables/compare/bug-33
Now we need a patch to fix it.
BTW I don't think the issue is in the regExpQuote function. This is only used to escape some characters. The problem must be lower
find-unused-sass-variables/index.js
Lines 54 to 58 in 7ffbc30
I see that there is already a branch with a solution. My thought was to expand the regex a little bit like this:
https://codepen.io/khazl/pen/abomveN?editors=0012
https://regex101.com/r/q4ghUJ/1
But using postCSS features seems smarter.