【问题标题】:Find out which identifiers are unresolved in a tsx script找出 tsx 脚本中未解析的标识符
【发布时间】:2018-11-29 05:19:00
【问题描述】:

我目前正在为 Web 应用程序开发自定义构建器。 现在需要自动检测导入,所以我需要知道tsx源代码中哪些标识符是未解析的,这样我的脚本才能导入正确的模块。

我目前正在研究的解决方案是遍历脚本的 AST,将声明的标识符存储在当前处理的范围内,然后返回未解析的标识符。但这需要大量工作来处理不同类型的 AST 元素。

因此,由于 tsc 和 ts 后台服务器都内置了这样的功能。我想知道是否有人可以告诉我他们是如何做到的,或者至少是在哪里做的,因为我找不到特定的代码。

谢谢

卢卡

【问题讨论】:

    标签: typescript abstract-syntax-tree tsx typescript-compiler-api


    【解决方案1】:

    我想我找到了一种解决方案。使用 AST 并不是那么容易,我遇到了一些难以解决的情况,在这些情况下很难确定哪个标识符对当前范围有效。

    所以我正在使用 typescript 编译器来获取错误消息。过滤每条错误消息并解析错误消息以获取标识符名称。这并不漂亮,但它有效。我还看到,在诊断 SourfeFileObjects 发生错误后,还包括导出的标识符。我也需要这些,但我是直接通过 AST 获取的。

    let compilerHost = {
        getSourceFile: (fname: string) => {...},
        writeFile: (name: string, text: string) => {...},
        getDefaultLibFileName: () => Path.join(__dirname, "node_modules/typescript/lib/lib.d.ts"),
        useCaseSensitiveFileNames: () => false,
        getCanonicalFileName: (fileName : string) => fileName,
        getCurrentDirectory: () => "",
        getNewLine: () => "\n",
        fileExists: (fname: string): boolean => {...},
        readFile: (fileName: string) => {...},
        directoryExists: (dname: string) => {...},
        getDirectories: () => []
    };
    
    let unresolved = []
    let sourceFile = TS.createSourceFile(filepath, tsCode, TS.ScriptTarget.ES5, true, TS.ScriptKind.TSX);
    let program = TS.createProgram([filepath], tsCompilerOptions, compilerHost);
    let semanticDiagnostic = program.getSemanticDiagnostics();
    if(semanticDiagnostic.length){
        unresolved = <string[]>semanticDiagnostic
            // Filter for Unresolved names
            .filter(m=>m.code == 2304 && m.file == this.sourceFile)
            .map(m=>{
                let matches = (m.messageText as string).match(/^Cannot find name '([A-Z]\w+)'.$/)
                if(matches){
                    return matches[1];
                }
            })
            .filter(sym=>typeof(sym)=="string");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多