Restructure props
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function (fileInfo, api) { | |
const j = api.jscodeshift; | |
return j(fileInfo.source) | |
.find(j.FunctionDeclaration) | |
.forEach((path) => { | |
const params = path.value.params; | |
if (params.length === 1 && params[0].type === "Identifier" && params[0].name === "props") { | |
const propsParam = params[0]; | |
const propsUsages = j(path).find(j.Identifier, { name: "props" }); | |
const propsNames = new Set(); | |
propsUsages.forEach((propsPath) => { | |
if ( | |
propsPath.parentPath.value.type === "MemberExpression" && | |
propsPath.parentPath.value.object === propsPath.value | |
) { | |
propsNames.add(propsPath.parentPath.value.property.name); | |
propsPath.parentPath.replace(propsPath.parentPath.value.property); | |
} | |
}); | |
propsParam.type = "ObjectPattern"; | |
propsParam.properties = Array.from(propsNames).map((name) => | |
j.property("init", j.identifier(name), j.identifier(name)) | |
); | |
} | |
}) | |
.toSource(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment