首页 > 解决方案 > Typescript编译器,如何按名称获取导出的符号?

问题描述

按名称获取导出符号的最佳方法是什么?

波纹管是功能代码。但是,它似乎有点脆弱,因为我无法在不忽略类型系统的情况下从“sourceFile”获取“符号”。

  const sourceFile = tsprogram.getSourceFile('foo_file.ts');
  const fileSymbol = (sourceFile as any).symbol as ts.Symbol; // anything better her? 
  const  export = fileSymbol.exports.get('FooComponent');

标签: typescript-compiler-api

解决方案


使用类型检查器:

const fileSymbol = tsprogram.getTypeChecker().getSymbolAtLocation(sourceFile);
const fooComponentSymbol = fileSymbol?.exports.get('FooComponent');

请注意,fileSymbol当没有文件导出时,它将是未定义的。


推荐阅读