Skip to content

Instantly share code, notes, and snippets.

@Bestra
Last active March 7, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Bestra/488b7190e3e57bbfa95932a6ab01d1b8 to your computer and use it in GitHub Desktop.
Save Bestra/488b7190e3e57bbfa95932a6ab01d1b8 to your computer and use it in GitHub Desktop.
codemod for adding this._super() calls to component lifecycle hooks
/**
To use this file you'll need to have `jscodeshift` (https://github.com/facebook/jscodeshift)
installed, which you can get through npm or yarn.
You can invoke it as follows:
`jscodeshift -t add-super-calls.js ~/path/to/js/files/`
You can pass `-d` to do a dry-run.
*/
const hookNames = [
'init',
'didInitAttrs',
'didReceiveAttrs',
'willRender',
'didInsertElement',
'didRender',
'didUpdateAttrs',
'didReceiveAttrs',
'willUpdate',
'willRender',
'didUpdate',
'didRender',
'willDestroyElement',
'willClearRender',
'didDestroyElement'
];
const spreadSuperMatcher =
{
callee:
{
object: { type: "ThisExpression" },
property: { name: "_super" }
}
}
const applySuperMatcher =
{
callee:
{
object:
{
object: { type: "ThisExpression" },
property: { name: "_super" }
},
property: { name: "apply" }
}
};
const not = function (fn) {
return function () { return !fn.apply(this, arguments) }
};
export default function transformer(file, api) {
const j = api.jscodeshift;
const hasSuperCall = function (node) {
let spreadCalls = j(node).find(j.CallExpression, spreadSuperMatcher);
let applyCalls = j(node).find(j.CallExpression, applySuperMatcher);
return spreadCalls.paths().length || applyCalls.paths().length;
};
const {expression, statement, statements} = j.template;
const componentDefinition = j(file.source)
.find(j.ExportDefaultDeclaration)
.find(j.CallExpression, {
callee:
{
property:
{ name: "extend" }
}
});
const functionHooks = componentDefinition
.find(j.Property, { value: { type: "FunctionExpression" } })
.filter(h => {
return hookNames.indexOf(h.node.key.name) > -1
});
let noSuper = functionHooks.filter(not(hasSuperCall));
let newColl = noSuper.replaceWith(({node}) => {
api.stats("needs super call");
console.log(`${file.path}:${node.loc.start.line} ${node.key.name}`);
node.value.body.body.unshift("this._super(...arguments);");
return node;
});
return newColl.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment