Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JLHwung
Created August 17, 2021 14:57
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 JLHwung/1f7e3234b960a6ffdd58e3b100cb9020 to your computer and use it in GitHub Desktop.
Save JLHwung/1f7e3234b960a6ffdd58e3b100cb9020 to your computer and use it in GitHub Desktop.
Transform @babel/types namespace import to named import
/**
input
```
import * as t from "@babel/types"
t.isIdentifier(node)
```
output
```
import { isIdentifier } from "@babel/types"
isIdentifier(node)
```
This codemod tries to preserve whitespaces. After running this codemod, please run prettier to reformat.
*/
const glob = require("glob");
const parse = require("@babel/parser").parse;
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const fs = require("fs");
glob(process.argv[2], (err, matches) => {
if (err) {
throw err;
}
const seenMethods = new Set();
for (const match of matches) {
let input = fs.readFileSync(match, { encoding: "utf-8" });
if (input.includes(`import * as t from "@babel/types"`)) {
seenMethods.clear();
traverse(
parse(input, {
plugins: [match.endsWith(".ts") ? "typescript" : "flow"],
sourceType: "module",
}),
{
MemberExpression(path) {
const { node } = path;
if (
node.computed === false &&
t.isIdentifier(node.object, { name: "t" })
) {
const { property } = node;
seenMethods.add(property.name);
}
},
}
);
const seenMethodLists = [...seenMethods.values()];
seenMethodLists.sort();
let newSpecifiers = "";
if (seenMethodLists.length === 0) {
newSpecifiers = `import type * as t from "@babel/types"`;
} else {
newSpecifiers = `import { `;
for (const method of seenMethodLists) {
if (method === "super") {
newSpecifiers += "super as _super, ";
input = input.replaceAll(/(\W+)t\.super/g, "$1_super");
} else {
newSpecifiers += method + ", ";
input = input.replaceAll(
new RegExp("(\\W+)t\\." + method, "g"),
"$1" + method
);
}
}
newSpecifiers += ` } from "@babel/types";`;
if (input.match(/\W+t\./)) {
// has type import;
newSpecifiers += `\nimport type * as t from "@babel/types";`;
}
}
input = input.replace(`import * as t from "@babel/types"`, newSpecifiers);
fs.writeFileSync(match, input);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment