Skip to content

Instantly share code, notes, and snippets.

@vamshi9666
Created June 13, 2022 12:32
Show Gist options
  • Save vamshi9666/4a1aa9c736ee0caa9a647bf5041c3bbf to your computer and use it in GitHub Desktop.
Save vamshi9666/4a1aa9c736ee0caa9a647bf5041c3bbf to your computer and use it in GitHub Desktop.
// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = "tsx";
const allStyleProps = ["bg", "margin", "lineHeight", "padding", "fontWeight"];
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
const componentsImportedFromChakraUi = root
.find(j.ImportDeclaration, {
source: {
value: "@chakra-ui/react",
},
})
.nodes();
root.find(j.JSXElement).forEach((path) => {
const node = path.node;
const openingElement = node.openingElement;
const name = openingElement.name;
// if the component is not in the chakra-ui library, skip it
if (
componentsImportedFromChakraUi.find((component) =>
component.specifiers.find(
(specifier) => specifier.local.name === name.name
)
)
) {
const props = node.openingElement.attributes;
const propsWithNames = props.filter((r) => r && r.name && r.name.name);
console.log(
"styles are ",
propsWithNames
);
// check if any props are included in styleProps
const styleProps = propsWithNames.filter((prop) =>
allStyleProps.includes(prop.name.name)
);
if (styleProps.length > 0) {
// if so, add style prop
const newCssprop = j.jsxAttribute(
j.jsxIdentifier("css"),
j.jsxExpressionContainer(
j.objectExpression(
styleProps.map((prop) => {
console.log("value", Object.keys(prop));
return j.objectProperty(
j.identifier("name"),
j.literal("prop.value.expression.value")
);
})
)
)
);
openingElement.attributes.push(newCssprop);
}
}
});
return root.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment