Skip to content

Instantly share code, notes, and snippets.

@maparent
Last active March 18, 2019 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maparent/83dfd65a37aaaabc4072b30b67d5a05d to your computer and use it in GitHub Desktop.
Save maparent/83dfd65a37aaaabc4072b30b67d5a05d to your computer and use it in GitHub Desktop.
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