Open Ayc0 opened 4 years ago
I tried to look into jscodeshift and recast (and sub packages) to see if I could patch the traverse / visit / walk / whatever function but every time I can only see this.traverse
without defining traverse
so I gave up
but if someone could help me on this, I'd be glad to work on a PR
I believe this is blocked by https://github.com/benjamn/ast-types/issues/343
Sandbox returns 404.
I switched to using @babel/traverse
instead. I already use it as a parser so I might as well use their traversal helper to ensure the understanding of the tree is consistent between parsing and traversal.
jscodeshift find:
const refObjectTypeReferences = ast
.find(j.TSTypeReference, (typeReference) => {
const { typeName } = typeReference;
if (typeName.type === "TSTypeParameter") {
// TODO: What code produces this AST?
return false;
} else {
const identifier =
typeName.type === "TSQualifiedName"
? /** @type {any} */ (typeName.right)
: typeName;
return ["RefObject"].includes(identifier.name);
}
})
@babel/traverse
:
/**
* @type {import('@babel/types').TSTypeReference[]}
*/
const refObjectTypeReferences = [];
traverse(ast.get("program").value, {
TSTypeReference({ node: typeReference }) {
const { typeName } = typeReference;
const identifier =
typeName.type === "TSQualifiedName" ? typeName.right : typeName;
if (["RefObject"].includes(identifier.name)) {
refObjectTypeReferences.push(typeReference);
}
},
});
I can even get rid of an any
cast and one branch (typeName.type === "TSTypeParameter"
) that seemed unreachable anyway.
So this feels like I'm fixing 3 issues at once by switching to @babel/traverse
.
Sandbox returns 404.
I don't know why it's not available anymore, here is a new sandbox in ASTExplorer: https://astexplorer.net/#/gist/191f77988f260ee6bef6ec402331ac0e/808e05a888e206dacc16f8dac85609a7ac09eeab
And if the history goes away:
With:
JavaScript
,recast
,jscodeshift
const [state, setState] = React.useState<Enum.A | Enum.B | null>(null);
Transformer code:
// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = "tsx";
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
console.log(root.find("TSQualifiedName").nodes());
return root.toSource();
}
I get this output:
Description
jscodeshift(file.source).find
doesn't find anything in a generic.Example
Code sandbox: https://codesandbox.io/s/unruffled-goodall-b5qknEdit: ASTExplorer: https://astexplorer.net/#/gist/191f77988f260ee6bef6ec402331ac0e/808e05a888e206dacc16f8dac85609a7ac09eeab
Input
Traverse
And it should match 2 things :
Enum.A
andEnum.B
AST
Versions