babel-plugin-styled-components-enhancer
v1.3.0
Published
Add custom syntax to `styled-components` template literals You opt-in via the `stld` template literal, so you can use both syntaxes at once
Downloads
7
Readme
Babel Plugin: Styled Components Enhanced
Add custom syntax to styled-components
template literals
You opt-in via the stld
template literal, so you can use both syntaxes at once
NOTE: You still need to import styled from 'styled-components'
even if it's not used in the file (similar to how you'd import React when using JSX)
Examples:
A more complex example can be run by node run-example.js
(after installing dev dependencies)
Replace all rem number values with a custom imported handler
// source.js
const A = stld.span`
border: 1px dotted $themeRed;
background: $themeBlue;
${() => css`color: $themeMagenta;`} /* works recursively as well */
`;
// configure plugin:
babel.transform({
plugins: [
['styled-components-enhanced', {
transform: [
// use theme color: replaces "$themeBlue" --> ${({theme}) => theme.colors.blue}
{
match: [/\$theme([A-Za-z0-9]+)/.source, 'g'],
template: '({theme}) => theme.colors.$1',
},
],
}],
],
})
Result:
const A = styled.span`
border: 1px dotted ${({theme}) => theme.colors.Red};
background: ${({theme}) => theme.colors.Blue};
${() => css`color: ${({theme}) => theme.colors.Magenta};`} /* works recursively as well */
`;
Options
- [id] The Identifier to use (Default:
stld
) - [parseRootCss] By default, only
css
templates withing astyled
template literal will be evaluated. This option enables parsingcss
templates regardless. (Default:false
) - transform (required) An array of transformations
- match RegExp to look for. The result of
.match()
is passed as arguments to replace (required) - template A template string to replace with. Every result from the regexp match above will be passed as values $0, $1 etc
- match RegExp to look for. The result of
- [recursive] Whether to recursively apply the transforms in inner templates (Default:
true
) - [recursiveTags] Which tags to recursively traverse (Default:
['css']
)