-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add tsconfig.json parsing capability
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import * as Path from "path"; | ||
|
||
import ts, { ParsedCommandLine, Program } from "typescript"; | ||
|
||
import { Project } from "../project/Project"; | ||
|
||
|
||
export class TypeScriptConfiguration { | ||
private static parseFile(filePath: string): ParsedCommandLine { | ||
const file: any = ts.readConfigFile(filePath, ts.sys.readFile); | ||
|
||
if (file.error) { | ||
throw new Error("Error reading tsconfig.json."); | ||
} | ||
|
||
const parsedCommandLine: ParsedCommandLine = ts.parseJsonConfigFileContent( | ||
file.config, | ||
ts.sys, | ||
Path.dirname(filePath) | ||
); | ||
|
||
if (parsedCommandLine.errors.length > 0) { | ||
throw new Error(`Error parsing tsconfig.json: ${JSON.stringify(parsedCommandLine.errors)}.`); | ||
} | ||
|
||
return parsedCommandLine; | ||
} | ||
|
||
private readonly filePath: string; | ||
|
||
public constructor(project: Project) { | ||
this.filePath = Path.join(project.getPath(), "tsconfig.json"); | ||
} | ||
|
||
public getEmittedDirectory(): string { | ||
const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath); | ||
const emittedDirectory: string | undefined = parsedCommandLine.options.outDir; | ||
|
||
if (!emittedDirectory) { | ||
throw new Error("No `outDir` configuration in tsconfig.json."); | ||
} | ||
|
||
return emittedDirectory; | ||
} | ||
|
||
public getCompiledDirectoryStructure(): Array<string> { | ||
const parsedCommandLine: ParsedCommandLine = TypeScriptConfiguration.parseFile(this.filePath); | ||
|
||
const program: Program = ts.createProgram({ | ||
rootNames: parsedCommandLine.fileNames, | ||
options: parsedCommandLine.options, | ||
}); | ||
|
||
const emittedFilePaths: Array<string> = new Array<string>(); | ||
const emittedDirectory: string = this.getEmittedDirectory(); | ||
|
||
program.emit(undefined, (fileName: string): void => { | ||
emittedFilePaths.push(fileName); | ||
}); | ||
|
||
return emittedFilePaths.map((filePath: string): string => { | ||
return Path.relative(emittedDirectory, filePath).replace(/\\/g, "/") | ||
}); | ||
} | ||
} |