A plugin for Babel that provides another syntax for getting access to styled-components props.
$ npm install --save-dev babel-plugin-styled-props-conditions
Add babel-plugin-styled-props-conditions
to plugins list in your .babelrc
:
{
"plugins": ["babel-plugin-styled-props-conditions"]
}
@if <prop_name> [<javascript code>] {
<styles>
}
This plugin searches for Tagged Templates Literals containing conditional blocks written with syntax described above. When blocks are found the plugin replaces them with ${expression}
blocks.
@if <prop_name> [<javascript code>] {
<styles>
}
${({ <prop_name> }) => <prop_name> [<javascript code>] && css`
<styles>
`}
styled.button`
@if primary {
color: green;
}
@if secondary {
color: grey;
}
`
Instead of
import { css } from 'styled-components';
styled.button`
${({ primary }) => primary && css`
color: green;
`}
${({ secondary }) => secondary && css`
color: grey;
`}
`
styled.button`
@if theme == 'light' {
color: black;
background-color: white;
}
@if theme == 'dark' {
color: white;
background-color: black;
}
@if theme == getTheme() {
color: ${getColor()};
}
`
Instead of
import { css } from 'styled-components';
styled.button`
${({ theme }) => theme == 'light' && css`
color: black;
background-color: white;
`}
${({ theme }) => theme == 'dark' && css`
color: white;
background-color: black;
`}
${({ theme }) => theme == getTheme() && css`
color: ${getColor()};
`}
`
styled.button`
@if primary {
@if theme == 'light' {
color: black;
background-color: white;
}
@if theme == 'dark' {
color: white;
background-color: black;
}
}
`
Instead of
import { css } from 'styled-components';
styled.button`
${({ primary }) => primary && css`
${({ theme }) => theme == 'light' && css`
color: black;
background-color: white;
`}
${({ theme }) => theme == 'dark' && css`
color: white;
background-color: black;
`}
`}
`
Check the example folder to see how this plugin works in the real project.
To make @if
keyword as known to stylelint, add
"ignoreAtRules": ["/^if$/"]
option to at-rule-no-unknown
rule in .stylelintrc
, like so:
{
"rules": {
"at-rule-no-unknown": [true, {
"ignoreAtRules": ["/^if$/"]
}]
}
}