Last active
August 9, 2020 12:11
-
-
Save ritwickdey/14d07f8f2aeefd9f7d18b67286047449 to your computer and use it in GitHub Desktop.
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
//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