Last active
December 2, 2024 05:12
-
-
Save laurenashpole/a7bdc373e97d4c1efd1eea1aa8ee4b0d to your computer and use it in GitHub Desktop.
A jscodeshift codemod for converting any Lodash imports into direct imports
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 root = j(fileInfo.source); | |
let specifiers = []; | |
root | |
.find(j.ImportDeclaration, isLodashImport) | |
.forEach((path) => specifiers.push(...path.node.specifiers.map((specifier) => specifier.local.name))) | |
.remove(); | |
root | |
.find(j.CallExpression, isLodashExpression) | |
.forEach((path) => specifiers.push(path.node.callee.property.name)) | |
.replaceWith((path) => replaceExpression(path, j)); | |
if (specifiers.length) { | |
cleanSpecifiers(specifiers).forEach((specifier) => { | |
root.find(j.Declaration).at(0).get() | |
.insertBefore(createImport(j, specifier)); | |
}); | |
} | |
return root.toSource(); | |
}; | |
function isLodashImport (node) { | |
return node.source.value.startsWith('lodash'); | |
} | |
function isLodashExpression (node) { | |
return node.callee.type === 'MemberExpression' && node.callee.object && node.callee.object.name === '_'; | |
} | |
function replaceExpression (path, j) { | |
return j.callExpression(j.identifier(path.node.callee.property.name), path.node.arguments); | |
} | |
function cleanSpecifiers (specifiers) { | |
return specifiers.filter((specifier, i) => { | |
return specifier !== '_' && specifiers.indexOf(specifier) === i; | |
}); | |
} | |
function createImport (j, specifier) { | |
return j.importDeclaration( | |
[j.importDefaultSpecifier(j.identifier(specifier))], | |
j.stringLiteral(`lodash/${specifier}`) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment