Skip to content

Instantly share code, notes, and snippets.

@popomore
Created April 26, 2017 14:07
Show Gist options
  • Save popomore/193d5c892bbf917a2882067aca8df745 to your computer and use it in GitHub Desktop.
Save popomore/193d5c892bbf917a2882067aca8df745 to your computer and use it in GitHub Desktop.
'use strict';
const jscodeshift = require('jscodeshift');
const { MemberExpression, Property } = jscodeshift;
jscodeshift.registerMethods({
// exports.a => exports.b
//
// jscodeshift(source)
// .find(jscodeshift.Identifier, { name: 'a' })
// .renamePropertyTo('b');
renamePropertyTo(name) {
return this.replaceWith(nodePath => {
const { node, parentPath } = nodePath;
const parentNode = parentPath.value;
// exports.a
if (MemberExpression.check(parentPath.value) && parentNode.property.name === node.name) {
updateNode(node, name);
}
// { a: 1 }
if (Property.check(parentPath.value) && parentNode.key.value === node.value) {
updateNode(node, name);
}
return node;
});
},
});
function updateNode(node, name) {
switch (node.type) {
case 'Identifier':
node.name = name;
break;
case 'Literal':
node.value = name;
break;
default:
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment