Max Heiber
Max Heiber

Reputation: 15502

How can I create human-readable JSON from TypeScript CompilerOptions?

Given an object like this:

import * as ts from "typescript";

const options: ts.CompilerOptions = {
    target: ts.ScriptTarget.ESNext,
    moduleResolution: ts.ModuleResolutionKind.NodeJs
}

How can I generate a human-readable tsconfig.json like this?

{
    "target": "ESNext",
    "moduleResolution": "NodeJs"
}

Alternatively, I could solve my problem if there is a way to go the other way around (parse a ts.CompilerOptions object from human-readable tsconfig input).

I'm asking this question because I'm trying to use the same object to generate both a tsconfig.json and an object to feed into the TS Compiler API.

Upvotes: 2

Views: 236

Answers (1)

Max Heiber
Max Heiber

Reputation: 15502

There's no way to do it!

But given the problem you're trying to solve, it looks like there is a solution:

Alternatively, I could solve my problem if there is a way to go the other way around (parse a ts.CompilerOptions object from human-readable tsconfig input).

I'm asking this question because I'm trying to use the same object to generate both a tsconfig.json and an object to feed into the TS Compiler API.

You can start with a JSON-style configuration object, where none of the values are enums, and use that to generate the tsconfig.json.

Then use ts.convertCompilerOptionsFromJson to convert the compiler options from the JSON-style object to a ts.CompilerOptions.

As an example, here's how gulp-typescript does the conversion:

import * as ts from "typescript";

// later in the file
const settingsResult = typescript.convertCompilerOptionsFromJson(settings, projectDirectory);

if (settingsResult.errors) {
    reportErrors(settingsResult.errors, typescript);
}

Upvotes: 2

Related Questions