Challenge 3: tsconfig
- TypeScript course
- Expert
- Lesson 34/35
- 6 min
Solve a task requiring a multi-project monorepo setup.
Multi-project tsconfig
In this challenge you will process a multi-project tsconfig structure. Parse a tsconfig JSON text with ts.parseConfigFileTextToJson, and access the compilerOptions and references fields. You will read and analyze a monorepo configuration.
Practice Read the target value
Given a tsconfig JSON text: target "ES2020", strict true, and include array with src/**/*.ts. Parse with ts.parseConfigFileTextToJson. Print the target value from the compiler options.
Starter code
import * as ts from "typescript";
// Bir tsconfig JSON metni ver: hedef "ES2020", strict true
// include dizisinde "src/**/*.ts" olsun
// parseConfigFileTextToJson ile çözümle
// Derleyici seçeneklerinden hedef değeri yazdır
// kodunu buraya yazSample solution
import ts from "typescript";
const configText = '{"compilerOptions": {"target": "ES2020", "strict": true}, "include": ["src/**/*.ts"]}';
const result = ts.parseConfigFileTextToJson("tsconfig.json", configText);
const target = (result.config?.compilerOptions as { target?: string })?.target;
console.log(target);Expected output
ES2020
Practice Count references
Given a tsconfig JSON text with three project references, path values ./shared, ./app, ./utils. Parse with ts.parseConfigFileTextToJson. Print the length of the references array.
Starter code
import * as ts from "typescript";
// Bir tsconfig JSON metni ver: üç proje referansı içersin
// path değerleri: "./shared", "./app", "./utils"
// parseConfigFileTextToJson ile çözümle
// Referans dizisinin uzunluğunu yazdır
// kodunu buraya yazSample solution
import ts from "typescript";
const configText = '{"references": [{"path": "./shared"}, {"path": "./app"}, {"path": "./utils"}]}';
const result = ts.parseConfigFileTextToJson("tsconfig.json", configText);
const refs = result.config?.references as Array<{ path: string }>;
console.log(refs.length);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which API is used to parse a tsconfig JSON text?
- ts.parseTsConfig
- ts.parseConfigFileTextToJson Correct answer
- ts.loadConfig
- ts.readTsConfig
Explanation: ts.parseConfigFileTextToJson takes a file name and config text, and returns the parsed JSON. readTsConfig, parseTsConfig and loadConfig do not exist.
2 Access the references array
const refs = result.config?.____ as Array<{ path: string }>;
const refs = result.config?.references as Array<{ path: string }>;
Explanation: In tsconfig, project references are given in the references array; projects, depends and imports are not tsconfig fields.
3 tsconfig parts
| Term | Meaning |
|---|---|
references |
Project dependencies |
compilerOptions |
Compiler settings |
include |
File patterns |
parseConfigFileTextToJson |
Parses config text |