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?
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.
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.
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.
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,
"./"
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With