Skip to content

Instantly share code, notes, and snippets.

@MrOrz
Created May 26, 2017 10:27
Show Gist options
  • Save MrOrz/4cb0f3d3cff7f7c5ff8327acd1148356 to your computer and use it in GitHub Desktop.
Save MrOrz/4cb0f3d3cff7f7c5ff8327acd1148356 to your computer and use it in GitHub Desktop.
This codemod script transforms all anonymous class expressions that extends `React`.* to named class declarations with their `displayName` static property.
/* Converts
export default class extends React.PureComponent {
static displayName = 'Calendar';
...
}
to this:
export default class Calendar extends React.PureComponent {
...
}
----
Usage:
jscodeshift -d -p -t moveDisplayNameToClass.js <path>
*/
module.exports = function(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ClassExpression, { superClass: { object: { name: 'React' } } })
.filter(p => {
const firstBody = p.value.body.body[0];
if (!firstBody) return false;
return firstBody.key.name === 'displayName';
})
.replaceWith(p => {
const displayName = p.value.body.body[0].value.value;
const newBody = p.value.body;
newBody.body = newBody.body.slice(1);
return j.classExpression(
j.identifier(displayName),
newBody,
p.value.superClass
);
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment