How to get `CompilerOptions` from `tsconfig.json`
Asked Answered
J

3

17

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?

Jambeau answered 16/12, 2018 at 17:9 Comment(0)
J
29

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,
  "./"
);
Jambeau answered 22/12, 2018 at 18:18 Comment(2)
Also, note that this solution doesn't require path to "tsconfig.json"! findConfigFile takes care of that and you can always pass "./" there.Burgoyne
I had issues with this answer resolving "extends" in my tsconfig and I discovered that I needed to pass in dirname(configFileName) to ts.parseJsonConfigFileContent for basePath, instead of just "./". Now it resolves everything properly.Josphinejoss
R
1

In my experience, passing any CompilerOptions is very buggy. You will lose a ton of your time. What I did, was passing an empty object as CompilerOptions. And that's quite enough to get the diagnostics or AST or whatever you need. Unless you need to actually compile programmatically.

Nevertheless, IIRC, I once have managed to pass my compiler options by just reading tsconfig.json with JSON.encode(fs.readFileSync('./tsconfig.json'))

Repress answered 16/12, 2018 at 21:8 Comment(1)
You might need npmjs.com/package/json5 if your tsconfig.json contains comments.Burgoyne
S
1

If you have the tsconfig.json content in hand, you can easily use convertCompilerOptionsFromJson.

For example:

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

You'll get the following output:

{ options: { module: 1, outDir: 'dist' }, errors: [] }
Substituent answered 28/5, 2020 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.