【问题标题】:How to get `CompilerOptions` from `tsconfig.json`如何从 `tsconfig.json` 获取 `CompilerOptions`
【发布时间】:2019-05-17 04:34:54
【问题描述】:

我正在使用 TypeScript 编译器 API。初始化程序时,我被要求提供一个CompilerOptions 对象。我想将CompilerOptions 用于给定的tsconfig.json 文件,但我似乎无法弄清楚获取此文件的正确方法。

我想我应该使用parseJsonConfigFileContent,但这也需要ParseConfigHostThey say 自己实现很容易,但特别是方法readDirectory 自己实现似乎相当复杂。据我所知,你需要返回某个目录下的所有TypeScript文件,占excludesincludes

当然,TypeScript 已经在内部的某个地方做到了这一点。如何使用默认的readDirectoryParseConfigHost

换一种说法:为给定的 TypeScript 项目获取 CompilerOptions 的最简单方法是什么?

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    根据我的经验,传递任何CompilerOptions 都是非常错误。你会浪费很多时间。我所做的是将一个空对象作为CompilerOptions 传递。这足以获得诊断或 AST 或任何您需要的东西。除非您需要以编程方式实际编译。

    尽管如此,IIRC,我曾经设法通过使用 JSON.encode(fs.readFileSync('./tsconfig.json')) 读取 tsconfig.json 来传递我的编译器选项

    【讨论】:

    【解决方案2】:

    通过以下代码,我能够轻松读取编译器选项。

    我还不知道这是否有任何限制,但它似乎工作正常,它只使用 Typescript 本身提供的东西:

    const configFileName = ts.findConfigFile(
      "./",
      ts.sys.fileExists,
      "tsconfig.json"
    );
    const configFile = ts.readConfigFile(configFileName, ts.sys.readFile);
    const compilerOptions = ts.parseJsonConfigFileContent(
      configFile.config,
      ts.sys,
      "./"
    );
    

    【讨论】:

    • 另外,请注意,此解决方案不需要“tsconfig.json”的路径! findConfigFile 负责处理,你可以随时通过 "./" 那里。
    • 我在解决 tsconfig 中的“扩展”时遇到了问题,我发现我需要将 dirname(configFileName) 传递给 ts.parseJsonConfigFileContent 以获取 basePath,而不仅仅是 "./"。现在它可以正确解决所有问题。
    【解决方案3】:

    如果您手头有tsconfig.json 的内容,您可以轻松使用convertCompilerOptionsFromJson

    例如:

    const compilerOptions = ts.convertCompilerOptionsFromJson({ module: 'commonjs', outDir: 'dist' }, '.');
    console.log(compilerOptions);
    

    您将获得以下输出:

    { options: { module: 1, outDir: 'dist' }, errors: [] }
    

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2016-05-07
      • 2016-05-16
      相关资源
      最近更新 更多