Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get `CompilerOptions` from `tsconfig.json`

I'm working with the TypeScript compiler API. When initializing a program, I'm asked to supply a CompilerOptions object. I want to use the CompilerOptions for a given tsconfig.json file, but I can't seem to figure out what the right way is to get this.

I think I'm supposed to use parseJsonConfigFileContent but that also needs a ParseConfigHost. They say that it's easy to implement yourself, but particularly the method readDirectory seems rather complicated to implement yourself. As far as I can see, you need to return all TypeScript files in a certain directory, accounting for a excludes and includes.

Surely, TypeScript does this internally somewhere already. How can I use the default readDirectory or ParseConfigHost?

Phrased in another way: what's the simplest way to get the CompilerOptions for a given TypeScript project?

like image 910
Werner de Groot Avatar asked Dec 16 '18 17:12

Werner de Groot


People also ask

What are compileroptions in Tsconfig json?

The tsconfig.json file specifies the root files and the compiler options required to compile the project. JavaScript projects can use a jsconfig.json file instead, which acts almost the same but has some JavaScript-related compiler flags enabled by default.

Where does TSC look Tsconfig?

When using the tsc command to compile files, if a path to tsconfig. json is not specified, the compiler will look for the file in the current directory. If not found in the current directory, it will search for the tsconfig. json file in the parent directory.

How do you reference Tsconfig?

Simply place a tsconfig. json file in each subdirectory of a given parent folder, and add reference s to these config files to match the intended layering of the program. You will need to either set the outDir to an explicit subfolder of the output folder, or set the rootDir to the common root of all project folders.


1 Answers

With the following code I was able to easily read the compiler options.

I don't yet know if this has any limitations, but it seems to work fine and it only uses things that Typescript itself provides:

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,
  "./"
);
like image 170
Werner de Groot Avatar answered Sep 20 '22 20:09

Werner de Groot