Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Last active August 9, 2020 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/14d07f8f2aeefd9f7d18b67286047449 to your computer and use it in GitHub Desktop.
Save ritwickdey/14d07f8f2aeefd9f7d18b67286047449 to your computer and use it in GitHub Desktop.
//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