gpt4 book ai didi

typescript-compiler-api - Typescript 转换器, `node.parent` 未定义

转载 作者:行者123 更新时间:2023-12-05 03:44:09 26 4
gpt4 key购买 nike

我目前正在使用 typescript transformer api,我发现 node.parent 是未定义的。

我的代码是:

        const transformerFactory: ts.TransformerFactory<ts.Node> = (
context: ts.TransformationContext
) => {
return (rootNode) => {
function visit(node: ts.Node): ts.Node {
node = ts.visitEachChild(node, visit, context);

// HERE node.parent IS UNDEFINED !

return filterFn(node, context);


}

return ts.visitNode(rootNode, visit);
};
};

const transformationResult = ts.transform(
sourceFile, [transformerFactory]
);

如何找到节点的父节点?

最佳答案

可以解析指定设置父节点:

const sourceFile = ts.createSourceFile(
"fileName.ts",
"class Test {}",
ts.ScriptTarget.Latest,
/* setParentNodes */ true, // specify this as true
);

或者在节点上做一些操作来设置它的父节点(例如类型检查程序... IIRC 在绑定(bind)期间确保设置父节点)。

根据评论更新

如果您从程序中创建这些,那么您可以执行以下操作:

const options: ts.CompilerOptions = { allowJs: true };
const compilerHost = ts.createCompilerHost(options, /* setParentNodes */ true);
const program = ts.createProgram([this.filePath], options, compilerHost);

关于typescript-compiler-api - Typescript 转换器, `node.parent` 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66604211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com