eslint-plugin-csstyper
TypeScript icon, indicating that this package has built-in type declarations

0.3.2 • Public • Published

Eslint Plugin CSSTyper

This eslint plugin warns you if CSS values are invalid. This allows for the validation of interpolated CSS values in Styled Components. The plugin makes use of the Typescript compiler to infer types and csstree for validation. Errors are reported with eslint.

It reports the following errors:

  • CSSProperty objects used as values
  • Invalid CSS values
  • Usage of double functions: () => () => string

This rule is designed to be helpful while not slowing you down. If it encounters a function, it will check its return type. If that return type is a string, or any, it will not report an error. If the expression type is a string literal, numberm or union of these types, it will validate all possible combinations with csstree.

Examples:

let isPrimary = false
const backPos = isPrimary ? 'left' : 100 > 1 ? 'right' : 'white'
export const Button = styled('button')`
  /* Invalid -- backPos interpolation is in incorrect location */
  background: 5% / 15% ${120 / 2}% ${backPos} repeat-x url('star.png');
  /* Valid */
  background: ${backPos} 5% / 15% ${120 / 2}% repeat-x url('star.png');
  /* Invalid */
  color: ${props.primary ? 'blue' : 'superwhite'};
`

Using style objects is a good way to share config across your application. For strict typing of these values with csstyper, be sure to use as const.

const theme = {
  small: '5em'
} as const

interface Props {
  big?: 10
}

export const Div = (props => styled.div`
  color: red;
  /* Invalid -- 5empx is not valid for width */
  width: ${props.big || theme.small}px;
`)({} as Props)

Usage

This eslint-plugin has peer dependencies on typescript, @typescript-eslint/parser.

To install everything:

yarn add eslint @typescript-eslint/parser eslint-plugin-csstyper

Example .eslintrc

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "project": "./tsconfig.json",
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "plugins": ["@typescript-eslint", "csstyper"],
  "rules": {
    "csstyper/value": "error"
  }
}

Config

By default element units are allowed.

const bar = '3emax'
const Span = styled.span`
  font-size: ${bar};
`
.Span {
  font-size: calc(3 * var(--emax));
}

This can be disabled by setting the config option to false:

{
  "rules" {
    "csstyper/value": ["error", { "elementUnits": false}]
  }
}

License

Source code licensed with The Parity Public License 6.0.0

If you make modifications, be sure to contribute them back.

Readme

Keywords

none

Package Sidebar

Install

npm i eslint-plugin-csstyper

Weekly Downloads

194

Version

0.3.2

License

none

Unpacked Size

31.8 kB

Total Files

16

Last publish

Collaborators

  • brandonkal