Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chintan9/a1f8950719f8dd80b470bec75394b4c1 to your computer and use it in GitHub Desktop.
Save chintan9/a1f8950719f8dd80b470bec75394b4c1 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