【问题标题】:TypeScript Compiler API: how to get literal value by ImportSpecifier node?TypeScript Compiler API:如何通过 ImportSpecifier 节点获取文字值?
【发布时间】:2021-05-15 23:01:49
【问题描述】:

我有两个 TypeScript 文件。

常量.ts:

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>;
  }
}

我正在使用 TypeScript 编译器 API 来解析这些文件。我对这条线感兴趣:

static defaultProps = defaultProps;

在右侧我有带有kind=265(ImportSpecifier)的节点。如何从具有对象文字值的节点中获取?使用方法checker.getSymbolAtLocation(node) 返回undefined

【问题讨论】:

  • 如何使用编译器 API?只是好奇。很有趣的话题

标签: typescript typescript-compiler-api


【解决方案1】:

它不是获取导入说明符的符号,而是获取导入说明符名称(标识符)的符号。不过,这只是 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());

【讨论】:

  • 谢谢,这正是我需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多