Created
November 11, 2019 22:56
-
-
Save Gerrit0/1c7445ec5a23c656a86e0cc21c790941 to your computer and use it in GitHub Desktop.
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
import * as ts from 'typescript' | |
import { resolve } from 'path' | |
const options: ts.CompilerOptions = { | |
declaration: true, | |
emitDeclarationOnly: true, | |
allowJs: true, // I treat jsw as js | |
// ... | |
} | |
class Host implements ts.CompilerHost { | |
private sourceFiles = new Map<string, ts.SourceFile>() | |
getSourceFile( | |
fileName: string, | |
languageVersion: ts.ScriptTarget | |
): ts.SourceFile | undefined { | |
const canonical = resolve(this.getCurrentDirectory(), this.getCanonicalFileName(fileName)); | |
const existing = this.sourceFiles.get(canonical) | |
if (existing) return existing; | |
const content = this.readFile(canonical); | |
if (content === undefined) return undefined; | |
const parsed = ts.createSourceFile(canonical, content, languageVersion) | |
this.sourceFiles.set(canonical, parsed); | |
return parsed; | |
} | |
getDefaultLibFileName(options: ts.CompilerOptions): string { | |
return ts.getDefaultLibFileName(options); | |
} | |
writeFile( | |
fileName: string, | |
data: string, | |
writeByteOrderMark: boolean, | |
_onError?: (message: string) => void, | |
_sourceFiles?: readonly ts.SourceFile[] | |
): void { | |
// Should probably catch errors. | |
ts.sys.writeFile(fileName, data, writeByteOrderMark); | |
} | |
getCurrentDirectory(): string { | |
return ts.sys.getCurrentDirectory(); | |
} | |
getCanonicalFileName(fileName: string): string { | |
return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase(); | |
} | |
useCaseSensitiveFileNames(): boolean { | |
return ts.sys.useCaseSensitiveFileNames; | |
} | |
getNewLine(): string { | |
return ts.sys.newLine; | |
} | |
fileExists(fileName: string): boolean { | |
if (fileName.endsWith('.js')) { | |
return ts.sys.fileExists(fileName + 'w') || ts.sys.fileExists(fileName) | |
} | |
return ts.sys.fileExists(fileName); | |
} | |
readFile(fileName: string): string | undefined { | |
if (fileName.endsWith('.js') && ts.sys.fileExists(fileName + 'w')) { | |
return ts.sys.readFile(fileName + 'w') | |
} | |
return ts.sys.readFile(fileName) | |
} | |
} | |
const host = new Host() | |
const program = ts.createProgram({ | |
rootNames: ['./src/index.ts'], | |
host, | |
options, | |
}) | |
program.emit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment