TypeScript编译器API:如何通过ImportSpecifier节点获取文本值?
我有两个打字脚本文件 常数:TypeScript编译器API:如何通过ImportSpecifier节点获取文本值?,typescript,typescript-compiler-api,Typescript,Typescript Compiler Api,我有两个打字脚本文件 常数: export const defaultProps = { name: 'Node' }; MyComponent.tsx: import * as React from 'react'; import {defaultProps} from './const'; interface MyCompProps { name: string; } export class MyComp extends React.Component<MyComp
export const defaultProps = {
name: 'Node'
};
MyComponent.tsx:
import * as React from 'react';
import {defaultProps} from './const';
interface MyCompProps {
name: string;
}
export class MyComp extends React.Component<MyCompProps> {
static defaultProps = defaultProps;
constructor(props: MyCompProps) {
super(props);
}
render() {
const {name} = this.props;
return <div>{name}</div>;
}
}
在右侧,我有一个节点,其类型为
kind=265
(ImportSpecifier)。如何使用对象的文本值从it节点获取?使用方法checker.getSymbolAtLocation(node)
返回未定义的而不是获取导入说明符的符号,它可以获取导入说明符名称(标识符)的符号。但这只是MyComponent.tsx中的本地符号,因此您需要从中获取别名符号,在本例中,它将引导您在const.ts中找到defaultProps
变量声明:
const symbol = checker.getSymbolAtLocation(importSpecifier.name)!;
const aliasedSymbol = checker.getAliasedSymbol(symbol);
const varDecl = aliasedSymbol.getDeclarations()![0];
// outputs the `defaultProps` variable declaration
console.log(varDecl.getText());
如何使用编译器API?只是好奇。非常有趣的话题汉克斯,这正是我需要的!
const symbol = checker.getSymbolAtLocation(importSpecifier.name)!;
const aliasedSymbol = checker.getAliasedSymbol(symbol);
const varDecl = aliasedSymbol.getDeclarations()![0];
// outputs the `defaultProps` variable declaration
console.log(varDecl.getText());