npm.io
1.3.0 • Published 9 years ago

babel-plugin-styled-components-enhancer

Licence
MIT
Version
1.3.0
Deps
0
Vulns
0
Weekly
0

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 a styled template literal will be evaluated. This option enables parsing css 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
  • [recursive] Whether to recursively apply the transforms in inner templates (Default: true)
  • [recursiveTags] Which tags to recursively traverse (Default: ['css'])