如何使用TypeScript编译器API获取导入文件的所有源?

时间:2017-08-21 12:14:06

标签: typescript typescript-compiler-api

我正在尝试使用ts API解析TypeScript程序的AST。我没有创建程序和获取AST的麻烦,但奇怪的是,并非所有导入的模块都可以访问。

考虑以下文件结构,a.tsx是我的入口点:

.
├── a.tsx
├── b
│   └── index.tsx
└── c.tsx

如果我导入一个包含完整文件名的模块(不包括扩展名),它可以正常工作:

import { c } from './c';
// or
import { b } from './b/index';

但是在b模块的情况下,如果删除index部分(这是一个完全有效且有效的语法),模块将从程序源中消失。

import { b } from './b';

创建程序并解析AST的代码如下:

import * as ts from 'typescript';

const options: ts.CompilerOptions = {
    target: ts.ScriptTarget.ES2015,
    jsx: ts.JsxEmit.Preserve,
};

const program = ts.createProgram([process.argv[2]], options);
const sources = program.getSourceFiles();

sources.forEach((source: ts.SourceFile) => {
    const path_ = source.fileName;
    if (path_.indexOf('node_modules') === -1) {
        console.log(`parsing ${path_}`);
    }
});

来源由program.getSources()电话返回。 当a.tsx文件导入我的第一个片段上的模块时,我可以访问源中的所有三个节点,但如果我使用第二个表单(import .. from './b'),则源只包含模块的节点{ {1}}和a

是否有一些特定选项可以传递c

TypeScript版本是2.4.2。

0 个答案:

没有答案
相关问题