【问题标题】:How to make is not under 'rootDir' check with TS API?如何使用 TS API 检查不在“rootDir”下?
【发布时间】:2023-03-16 20:59:01
【问题描述】:

我正在使用 TypeScript API (3.8)。我注意到tsc 进行了一项检查,而 TS API 似乎没有这样做。

在构建程序时,如果设置了outDir和rootDir,如果在rootDir之外有模块的导入,tsc会报错,例如:

❯ yarn -s tsc --outDir dist
api/app.ts:3:8 - error TS6059: File '/Users/jasonkuhrt/hello/services/boo.ts' is not under 'rootDir' '/Users/jasonkuhrt/hello/api'. 'rootDir' is expected to contain all source files.

3 import '../services/boo'
         ~~~~~~~~~~~~~~~~~


Found 1 error.

但是,TS API 不会进行此项检查。

我不知道:

  1. 我做错了什么
  2. TS API 中存在错误
  3. TS API 中缺少一个功能

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    确保您正在检查程序的诊断程序。我可以通过检查 ts.getPreEmitDiagnostics(program) 获得您描述的诊断结果。

    复制代码

    这里有一些使用@ts-morph/bootstrap的复制代码:

    import { createProjectSync, ts, InMemoryFileSystemHost } from "@ts-morph/bootstrap";
    
    // file system setup
    const fileSystem = new InMemoryFileSystemHost();
    fileSystem.writeFileSync("/tsconfig.json", `{
        "compilerOptions": {
            "rootDir": "src",
            "outDir": "dist"
        }
    }`);
    fileSystem.writeFileSync("/src/file.ts", `import "../otherDir/file";`);
    fileSystem.writeFileSync("/otherDir/file.ts", `export class Test {}`);
    
    // create project and program
    const project = createProjectSync({
        tsConfigFilePath: "./tsconfig.json",
        fileSystem,
    });
    const program = project.createProgram();
    
    // output diagnostics
    const diagnostics = ts.getPreEmitDiagnostics(program);
    console.log(project.formatDiagnosticsWithColorAndContext(diagnostics));
    

    输出:

    src/file.ts:1:8 - error TS6059: File '/otherDir/file.ts' is not under 'rootDir' '/src'.
    'rootDir' is expected to contain all source files.
    
    1 import "../otherDir/file";
             ~~~~~~~~~~~~~~~~~~
    

    【讨论】:

    • 啊,是的!我查看了EmitAndSemanticDiagnosticsBuilderProgram 类型的所有诊断方法,但错过/忘记了这个静态方法。这是您第二次回答我的 TS API 问题,非常感谢@david-sherret! ??
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多