eslint-plugin-css-modules icon indicating copy to clipboard operation
eslint-plugin-css-modules copied to clipboard

Mark dynamically interpolated classes as used

Open amannn opened this issue 4 years ago • 0 comments

Example:

import clsx from 'clsx';
import styles from './Button.module.scss';

function Button({children, className, variant = 'primary', ...rest}) {
  return (
    <button
      className={clsx(
        className,
        styles.root,
        styles[`root_variant-${variant}`]
      )}
      type="button"
      {...rest}
    >
      {children}
    </button>
  );
}
@import '~styles/theme';

.root {
  &_variant {
    &-primary {
      background-color: $colorPrimary;
    }

    &-secondary {
      background-color: $colorSecondary;
    }
  }
}

eslint-plugin-css-modules reports this error:

Unused classes found in Button.module.scss: root_variant, root_variant-primary, root_variant-secondary, root_variant-primary-secondary eslint(css-modules/no-unused-class)

This is the most common case I find in the code bases I'm working on where I have to disable the rule.

I'd propose that in this case all selectors should be marked as visited that match the dynamic pattern. So basically .root_variant-${variant} would create a regex like /\.root_variant-.*/ that is matched against all selectors.

For a limited amount of such variants you can of course create an explicit mapping, but I'm having this situation often, also with props like color which can contain a multitude of values and therefore I'd like to avoid the mapping.

@atfzl I know you don't maintain this repository anymore, but would you be open to a PR if I'd provide a fix?

amannn avatar Aug 27 '21 07:08 amannn