Last active
November 30, 2020 05:41
-
-
Save robtarr/d23ba7e5c68d591a7ffddb3c1e7b4a70 to your computer and use it in GitHub Desktop.
jscodeshift - replace `_.thing(...)` with `thing(...)` and add `import {thing} from 'lodash'`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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