Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A jscodeshift transformer to make classes from Backbone extends declarations
// Transform backbone declaration to class
// follows https://github.com/jashkenas/backbone/issues/3560#issuecomment-248670605
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.VariableDeclaration)
.filter((path)=>{
var decl = path.node.declarations[0];
var init = decl.init;
return init && init.type=='CallExpression' && init.callee.property && init.callee.property.name=='extend' && init.callee.object && init.callee.object.name != '_' && init.callee.object.name != '$';
}).replaceWith((path) => {
var decl = path.node.declarations[0];
var init = decl.init;
const name = decl.id;
var superclass = init.callee.object;
const content = init.arguments[0];
const methods = [];
const initvars = [];
for (var val of content.properties) {
if (val.value.type == 'FunctionExpression') {
const isCons = val.key.name == 'constructor';
const method = j.methodDefinition(isCons?'constructor': 'method', j.literal(val.key.name), val.value, false);
method.comments = val.comments;
methods.push(method);
} else {
initvars.push(val);
}
}
if (initvars.length > 0) {
superclass = j.callExpression(
j.memberExpression(superclass, j.identifier('extend'), false),
[j.objectExpression(initvars)]);
}
const cls = j.classDeclaration(name, j.classBody(methods), superclass);
cls.comments = path.node.comments;
return cls;
}).toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.