【问题标题】:Get all possible exports from module by TypeScript API or ts-morph通过 TypeScript API 或 ts-morph 从模块中获取所有可能的导出
【发布时间】:2021-10-09 11:40:26
【问题描述】:
// sourceFileContent
import path from 'path';
// Short version of node_modules/@types/node/path.d.ts
declare module 'path' {
    namespace path {
        interface ParsedPath {}
        interface FormatInputPathObject {}
        interface PlatformPath {
            normalize(p: string): string;
            join(...paths: string[]): string;
            // other...
        }
    }
    const path: path.PlatformPath;
    export = path;
}

下面的代码是使用 ts-morph 编写的,它是 typescript 的包装器

const sourceFile = project.createSourceFile('source.ts', sourceFileContent);
const importDeclarations = sourceFile.getImportDeclarations();

// loop for importDeclarations
let symbol = importDeclaration.getImportClause().getSymbol();
symbol = typeChecker.getAliasedSymbol(symbol);
const exportSymbols = typeChecker.getExportsOfModule(symbol);
// {"ParsedPath" => SymbolObject, "FormatInputPathObject" => SymbolObject, "PlatformPath" => SymbolObject}

这里我得到了三个导出符号,但是我们知道normalizejoin 和其他应该存在于path 模块中的函数。

import { normalize, join } from 'path'; // no errors

所以我一直在获取这些功能(normalizejoin 等),你能帮忙吗 使用 ts-morph 或裸 typescript API 从模块中获取所有可能的导出?

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    我不确定如何使用符号来执行此操作,但可以通过检查 path 对象的类型来获取其属性:

    const defaultImport = importDeclaration.getDefaultImportOrThrow();
    const defaultImportType = defaultImport.getType();
    
    for (const property of defaultImportType.getProperties()) {
      console.log(property.getName());
    }
    

    输出:

    normalize
    join
    resolve
    isAbsolute
    relative
    dirname
    basename
    extname
    sep
    delimiter
    parse
    format
    toNamespacedPath
    posix
    win32
    

    【讨论】:

      【解决方案2】:

      通过 ts-node 进行交互式打字稿会话:

      $ npx ts-node
      > import path from 'path'
      {}
      > Object.keys(path)
      [
        'resolve',    'normalize',
        'isAbsolute', 'join',
        'relative',   'toNamespacedPath',
        'dirname',    'basename',
        'extname',    'format',
        'parse',      'sep',
        'delimiter',  'win32',
        'posix',      '_makeLong'
      ]
      > 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-12
        • 2018-01-20
        • 1970-01-01
        • 2017-09-25
        • 2017-04-03
        • 2019-03-09
        • 2020-12-14
        • 2021-01-29
        相关资源
        最近更新 更多