Skip to content

Instantly share code, notes, and snippets.

@robtarr
Last active November 30, 2020 05:41
Show Gist options
  • Save robtarr/d23ba7e5c68d591a7ffddb3c1e7b4a70 to your computer and use it in GitHub Desktop.
Save robtarr/d23ba7e5c68d591a7ffddb3c1e7b4a70 to your computer and use it in GitHub Desktop.
jscodeshift - replace `_.thing(...)` with `thing(...)` and add `import {thing} from 'lodash'`
export default (fileInfo, api) => {
const j = api.jscodeshift;
const methods = [];
const root = j(fileInfo.source);
const body = root.find(j.Program).get('body', 0).node;
const { comments } = body;
delete body.comments
root.get().node.comments = comments;
let result = root
.find(j.CallExpression, {
callee: {
type: 'MemberExpression',
object: { type: 'Identifier', name: '_' },
},
})
.replaceWith(nodePath => {
const { node } = nodePath;
const method = node.callee.property.name;
const newNode = j.callExpression(
j.identifier(method),
node.arguments
);
if (methods.indexOf(method) === -1) {
methods.push(method);
}
return newNode;
});
if (methods.length) {
const newImport = j.importDeclaration(
[j.importSpecifier(j.identifier(methods.join(', ')))],
j.literal('lodash')
);
root
.find(j.Statement)
.at(0)
.insertBefore(newImport);
}
return root.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment