Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//https://astexplorer.net/#/gist/6fa8fbfbc299ba7dcf27a83d50d89c26/3af7743eac480fd64e4b9013c9e0969097470959
export default function (babel) {
const { types: t } = babel;
return {
name: "ast-transform", // not required
visitor: {
ImportDeclaration(importPath) {
if (importPath.node.source.value !== "lodash") return;
const namedSpecifiers = importPath
.get("specifiers")
.filter((specifier) => !specifier.isImportDefaultSpecifier());
const program = importPath.find((node) => node.isProgram());
namedSpecifiers.forEach((specifier) => {
const name = specifier.node.imported.name;
const allRefs = specifier.scope.getBinding(name).referencePaths;
const newId = program.scope.generateUidIdentifier(name);
allRefs.forEach((ref) => {
ref.node.name = newId.name;
ref.addComment("leading", `${name} => ${newId.name}`);
});
const newSpecifier = t.importDefaultSpecifier(newId);
const imp = t.importSpecifier;
importPath.insertAfter(
t.importDeclaration([newSpecifier], t.stringLiteral("lodash/" + name))
);
});
importPath.remove();
program.addComment("leading", "lodash import modified");
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment