Skip to content

Instantly share code, notes, and snippets.

@laurenashpole
Last active March 26, 2023 10:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save laurenashpole/a7bdc373e97d4c1efd1eea1aa8ee4b0d to your computer and use it in GitHub Desktop.
Save laurenashpole/a7bdc373e97d4c1efd1eea1aa8ee4b0d to your computer and use it in GitHub Desktop.
A jscodeshift codemod for converting any Lodash imports into direct imports
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