babel-plugin-styled-props-conditions
A plugin for Babel that provides another syntax for getting access to styled-components props.
Installation
$ npm install --save-dev babel-plugin-styled-props-conditions
Usage
Add babel-plugin-styled-props-conditions
to plugins list in your .babelrc
:
Syntax
@if <prop_name> [<javascript code>] {
<styles>
}
How it works
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.
Input
@if <prop_name> [<javascript code>] {
<styles>
}
Output
${({ <prop_name> }) => <prop_name> [<javascript code>] && css`
<styles>
`}
Examples
Example #1: Boolean conditions
styledbutton` @if primary { color: green; } @if secondary { color: grey; }`
Instead of
; styledbutton` `
Example #2: Conditions with expressions
styledbutton` @if theme == 'light' { color: black; background-color: white; } @if theme == 'dark' { color: white; background-color: black; } @if theme == getTheme() { color: ; }`
Instead of
; styledbutton` `
Example #3: Nested conditions
styledbutton` @if primary { @if theme == 'light' { color: black; background-color: white; } @if theme == 'dark' { color: white; background-color: black; } }`
Instead of
; styledbutton` `
Real project example
Check the example folder to see how this plugin works in the real project.
Linting styles
To make @if
keyword as known to stylelint, add
"ignoreAtRules":
option to at-rule-no-unknown
rule in .stylelintrc
, like so: