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 esl
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.
``js
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.
`js
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)`
This eslint-plugin has peer dependencies on typescript, @typescript-eslint/parser.
To install everything:
`sh`
yarn add eslint @typescript-eslint/parser eslint-plugin-csstyper
Example .eslintrc
`json`
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json",
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": ["@typescript-eslint", "csstyper"],
"rules": {
"csstyper/value": "error"
}
}
By default element units are allowed.
`js
const bar = '3emax'
const Span = styled.span
font-size: ${bar};`
`css`
.Span {
font-size: calc(3 * var(--emax));
}
This can be disabled by setting the config option to false:
`json``
{
"rules" {
"csstyper/value": ["error", { "elementUnits": false}]
}
}
Source code licensed with The Parity Public License 6.0.0
If you make modifications, be sure to contribute them back.