no-duplicate-selectors error for different selectors inside the same file

2.8k Views Asked by At

I am using stylelint within a CSS-IN-JS project (here using astroturf, but I face the same pattern using any CSS-IN-JS library such as styled-components as well).

I define different styled elements within the same file, and therefore sometimes end up having duplicated selectors and/or import rules.

/* style.js */
import styled from 'astroturf';

export const StyledComponentA = styled('div')`
  transform: scale(0);

  &.visible {
    transform: scale(1);
  }
`;

export const StyledComponentB = styled('div')`
  opacity: 0;

  /* -> stylelint error: Unexpected duplicate selector "&.visible" */
  &.visible {
    opacity: 1;
  }
`;

Which I compose this way:

import React from 'react';
import { StyledComponentA, StyledComponentB } from './style';

export const Component = ({ isVisible }) => (
  <StyledComponentA visible={isVisible}>
    <StyledComponentB visible={isVisible}>Whatever</StyledComponentB>
  </StyledComponentA>
);

Is there a way to set these stylelint rules on blocks instead of an entire file?

1

There are 1 best solutions below

1
On BEST ANSWER

Is there a way to set these stylelint rules on blocks instead of an entire file?

There is not.

Rules like no-duplicate-selectors are scoped to a source and stylelint treats the following as sources:

  • entire files
  • code passed to the code option of the node API
  • stdin passed to the CLI

When writing CSS-in-JS, it might be advisable to turn off the rules scoped to sources. You can turn them off: