Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Forked from astexplorer/astexplorer.json
Created October 29, 2018 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/331793a601315ced89ee51fcebd62f13 to your computer and use it in GitHub Desktop.
Save cameronhunter/331793a601315ced89ee51fcebd62f13 to your computer and use it in GitHub Desktop.
Converting a glamorous-like API to React styled components: https://astexplorer.net/#/gist/a206145e34e9ec363df8c6cd5bd9de75/latest
{
"v": 2,
"parserID": "babylon7",
"toolID": "babelv7",
"settings": {
"babylon7": null
},
"versions": {
"babylon7": "7.0.0",
"babelv7": "7.0.0"
}
}
const Header = widget(
{
size: 30,
color: 'blue'
},
({ text, color }) => ({
text, color
})
);
export default function (babel) {
const { types: t } = babel;
return {
visitor: {
CallExpression(path) {
if (path.get('callee.name').node !== 'widget') {
return;
}
const calculateStyle = path.get('arguments.1');
const staticStyle = path.get('arguments.0');
const props = path.get('arguments.1.params.0.properties').map(p => p.node).map((n) => n.key.name);
path.replaceWithSourceString(`
(function createStyledComponent() {
const calculateStyle = ${calculateStyle};
const staticStyle = ${staticStyle};
const Component = function(props) {
return React.createElement(
'widget',
{
staticStyle: staticStyle,
style: calculateStyle(props)
},
props.children
);
};
const areEqual = function(prevProps, nextProps) {
if (prevProps === nextProps) return true;
return ${props.map((name) => `prevProps.${name} === nextProps.${name}`).join('&&')}
}
return React.memo(Component, areEqual);
}())
`);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment