Coder Social home page Coder Social logo

find-unused-sass-variables's Introduction

find-unused-sass-variables

npm version Build Status

A simple tool to check for unused Sass variables in a directory.

Install

npm install find-unused-sass-variables --save-dev

Usage

find-unused-sass-variables folder [, folder2...] --ignore "$my-var,$my-second-var" -e scss -e css --ignoreFiles file-with-unused-vars.scss
# or
fusv folder [, folder2...] --ignore "$my-var,$my-second-var" -e scss -e css --ignoreFiles file-with-unused-vars.scss

API

import { findAsync, find } from 'find-unused-sass-variables';

// 'directory' is a folder
const unused = find('directory');
// Array of unused variables
console.log(unused.unused);
// Array<{ name: string, line: string, file: string }>
/*
[
  {
    name = '$foo';
    file = 'file where this variable can be found';
    line = 'line of file';
  },
  {
    ....
  }
]
*/
// Total number of variables in the files
console.log(unused.total);
// Ignoring variables
const ignoredVars = ['$my-var', '$my-second-var'];
const unused = find('directory', { ignore: ignoredVars });
// Ignoring files
const ignoreFiles = ['./file-with-unused-vars.scss', '**/_variables.scss'];
const unused = fusv.find('directory', { ignoreFiles });
// Specifying file extensions
const unused = find('directory', { fileExtensions: ['css','scss']});
// Asynchronous usage
let unused = await findAsync('directory');

// or like a Promise
unused = findAsync('directory').then(result => {
  console.log(unused.unused);
});

find(dir, options)

  • dir: string
  • options: optional options Object

Returns an object with unused and total. unused has the array of unused variables and total has the sum of all variables in the files (unused and used ones).

findAsync(dir, options)

Returns a Promise which resolves result; returns the same as find(dir, options).

options.ignore

Array of strings of the variables to ignore, e.g. ['$my-var', '$my-second-var']

options.ignoreFiles

Array of strings of files to ignore, e.g. ['./file-with-unused-vars.scss', '**/_variables.scss'].

options.fileExtensions

Array of file extensions to search for unused variables in. e.g. ['scss']

Disable & enable

Disable or enable fusv with the fusv-disable and fusv-enable comments:

$used-variable-1: #666;

// fusv-disable
$unused-variable: #coffee;
// fusv-enable

$used-variable-2: #ace;

Notes

  • The tool's logic is pretty "dumb"; if you use the same name for a variable in different files or namespaces, then it won't distinguish between them.
  • The tool only looks for .scss files by default, but you can optionally specify the file extension.

License

MIT

find-unused-sass-variables's People

Contributors

b0jia avatar dependabot-preview[bot] avatar dependabot[bot] avatar geosot avatar johann-s avatar khazl avatar martijncuppens avatar xhmikosr avatar ysds avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

find-unused-sass-variables's Issues

Unused variable is not detected

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

Different number of variables on Windows/Linux shell

On Ubuntu:

> node ./cli.js tests/ --ignore="$a,$b"

Looking for unused variables
Searching for unused variables in "/home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests" folder, scss files...
11 total variables.
8 are not used!
Variable $a is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:2
Variable $b is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:3
Variable $unused is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:4
Variable $black is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:5
Variable $ignored-variable is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:13
Variable $enabled-variable is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:19
Variable $nestedVar is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/test.scss:7
Variable $nestNestedVar is not being used! /home/runner/work/find-unused-sass-variables/find-unused-sass-variables/tests/test.scss:12

On Windows:

> node ./cli.js tests/ --ignore="$a,$b"

Looking for unused variables
Searching for unused variables in "D:\a\find-unused-sass-variables\find-unused-sass-variables\tests" folder, scss files...
9 total variables.
6 are not used!
Variable $unused is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:4
Variable $black is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:5
Variable $ignored-variable is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:13
Variable $enabled-variable is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/_variables.scss:19
Variable $nestedVar is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/test.scss:7
Variable $nestNestedVar is not being used! D:/a/find-unused-sass-variables/find-unused-sass-variables/tests/test.scss:12

It seems that the ignore CLI option isn't respected on Linux. Maybe we need to escape $?

Wrong amount of variables.

After update to the latest version amount of total variables is zero.

Windows 10, command line inside IntelliJ IDEA
npm 9.6.7
node 18.17.1

C:\git\...>npx find-unused-sass-variables projects\quote-ui
Looking for unused variables

Searching for unused variables in "C:\git\...\projects\quote-ui" folder, scss files...
206 total variables
No unused variables found in "C:\git\...\projects\quote-ui"!

C:\git\...>npm install find-unused-sass-variables@latest

added 2 packages, and changed 3 packages in 5s

181 packages are looking for funding
  run `npm fund` for details

C:\git\...>npx find-unused-sass-variables projects\quote-ui
Looking for unused variables

Searching for unused variables in "C:\git\...\projects\quote-ui\src" folder, scss files...
0 total variables
No unused variables found in "C:\git\...\projects\quote-ui\src"!

Fails on files with UTF-8 with signature / 0xFEFF / BOM

Problem: Parser will yield errors like CssSyntaxError: <css input>:x:x: Unknown word

Quick fix: In file index.js change sassStr += fs.readFileSync(file, 'utf8'); to e.g.

let data = fs.readFileSync(file, 'utf-8');

// Remove 0xFEFF / BOM / UTF-8 with signature
if (data.startsWith("")) {
    data = data.substring(1);
}

sassStr += data;

Depending on the directory structure of 'node_modules', 'find' does not necessarily return results.

If the old version(example v7.0.13) of postcss installed in package, find() of find-unused-sass-variables is returned no result.
In this case, Declaration class referred to by find-unused-sass-variable and that referred to by postcss-scss are different.
Because, postcss-scss used old version(v7.0.13) of postcss and
find-unused-sass-variable used new version (v7.0.23 after) of postcss.
The node instance of Declaration always false in parse-variable.js.
The same applies to Comment class.

module path of Declaration class
postcss-scss /node_modules/postcss/lib/declaration.js
find-unused-sass-variables /node_modules/find-unused-sass-variables/node_modules/postcss/lib/declaration.js

examples: unused_test.zip

  1. npm install
  2. npm run test
    output console: { unused: [ '$unused1' ], total: 1 }
  3. npm install --save-dev [email protected]
  4. npm run test
    output console: { unused: [], total: 0 }

I'm not good at English.

node: v12.13.1
npm: v6.12.1

Switch to async functions

Except for fs.existsSync which isn't deprecated, but including glob.

EDIT:
We might need to switch to globby too.

Also, we should probably keep a fusv.sync method.

EDIT2: we can keep glob and use util.promisify probably.

Add an API

Maybe we should be able to do that in nodejs scripts :

const findUnusedSassVar = require('find-unused-sass-variables')
const folders = []
const unUsed = findUnusedSassVar.find(folders)

Ignore shouldn't modify the number of total variables

Currently, when we ignore a variable, it's removed from the total number of variables.

Not sure if it would make more sense to not change the total number of variables... Perhaps it should only change the number of unused variables only.

Handle the case where variables is null

H:\progs\dev\find-unused-sass-variables>node cli.js ..\..\
Looking for unused variables
i Finding unused variables in "H:\progs"...
H:\progs\dev\find-unused-sass-variables\index.js:35
    variables.forEach((variable) => {
              ^

TypeError: Cannot read property 'forEach' of null
    at Object.findUnusedVars [as find] (H:\progs\dev\find-unused-sass-variables\index.js:35:15)
    at args.forEach (H:\progs\dev\find-unused-sass-variables\cli.js:33:29)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (H:\progs\dev\find-unused-sass-variables\cli.js:28:6)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

postcss error

If a file has the following:

---
---

@charset "utf-8";

@import "vendor/normalize";

--- is needed for jekyll, then it throws

C:\Users\xmr\Desktop\foo\blog>fusv .
Looking for unused variables
i Finding unused variables in "C:\Users\xmr\Desktop\foo\blog"...

C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss\lib\parser.js:504
    throw this.input.error('Unknown word', tokens[0][2], tokens[0][3]);
    ^
CssSyntaxError: <css input>:1392:1: Unknown word
    at Input.error (C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss\lib\input.js:124:16)
    at ScssParser.unknownWord (C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss\lib\parser.js:504:22)
    at ScssParser.other (C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss\lib\parser.js:169:12)
    at ScssParser.parse (C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss\lib\parser.js:83:16)
    at scssParse (C:\Users\xmr\Desktop\find-unused-sass-variables\node_modules\postcss-scss\lib\scss-parse.js:11:10)
    at Object.findUnusedVars [as find] (C:\Users\xmr\Desktop\find-unused-sass-variables\index.js:30:24)
    at args.forEach (C:\Users\xmr\Desktop\find-unused-sass-variables\cli.js:33:29)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (C:\Users\xmr\Desktop\find-unused-sass-variables\cli.js:28:6)
    at Module._compile (internal/modules/cjs/loader.js:689:30)

Exit code (v0.4.0)

Shouldn't the script generate error when some unused variable is found ?

Spec :
Using Npm version

Expected behavior (0.3.3):
0 3 3

v0.4.0 behavior:
4 0

Add CLI

I have a branch with pretty basic CLI support. It works OK but I want to get rid of the global variable I'm using and then merge.

We could add a package like commander if needed, but preferably we should keep it as simple as possible since this tool is pretty dump.

Note to self: document caveats.

Add ignore file(s) support

Let's you ignore SCSS file(s):

Change in index.js

const sassFiles = glob.sync(path.join(dir, '**/*.scss'), { ignore: opt.ignoreFiles });

Usage:

const unused = fusv.find("./scss", { ignoreFiles: ["**/_crappy-vars.scss"], ignore: ["$crappy-var"] });`

Switch to async/await

We might need to switch to globby too.

Also, we could probably keep a fusv.sync method.

EDIT: we can keep glob and use util.promisify probably.

@import support

Hi guys,

I just did some tests with this tool, but ran into an issue when variables are used outside the folder that is scanned.

For example:

$variable: value;

@import "../path-outside-scanned-folder/variable-is-used-here.scss";

This will erroneously fail.

I tried to solve this, but then I realised #4 needed to be fixed first because a way to scan a file is needed.

main: process exit code is 0 even when unused variables are found

3.1.0:

C:\Users\xmr\Desktop\find-unused-sass-variables>fusv tests/ --ignore="$a,$b"
Looking for unused variables
Finding unused variables in "C:\Users\xmr\Desktop\find-unused-sass-variables\tests"...
9 total variables.
Variable $unused is not being used!
Variable $black is not being used!
Variable $ignored-variable is not being used!
Variable $enabled-variable is not being used!
Variable $nestedVar is not being used!
Variable $nestNestedVar is not being used!

C:\Users\xmr\Desktop\find-unused-sass-variables>echo %ERRORLEVEL%
1

main:

C:\Users\xmr\Desktop\find-unused-sass-variables>npm run test:cli

> [email protected] test:cli
> node ./cli.js tests/ --ignore="$a,$b"

Looking for unused variables
Searching for unused variables in "C:\Users\xmr\Desktop\find-unused-sass-variables\tests" folder, scss files...
9 total variables.
6 are not used!
Variable $unused is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/_variables.scss:4
Variable $black is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/_variables.scss:5
Variable $ignored-variable is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/_variables.scss:13
Variable $enabled-variable is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/_variables.scss:19
Variable $nestedVar is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/test.scss:7
Variable $nestNestedVar is not being used! C:/Users/xmr/Desktop/find-unused-sass-variables/tests/test.scss:12

C:\Users\xmr\Desktop\find-unused-sass-variables>echo %ERRORLEVEL%
0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.