-
-
Save damaon/c3ee658117aa72a3c15299f996880e68 to your computer and use it in GitHub Desktop.
jscodeshift - replace `_.thing(...)` with `thing(...)` and add `import {thing} from 'lodash'`
This file contains hidden or 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