Skip to content

Instantly share code, notes, and snippets.

@Gerrit0
Created November 11, 2019 22:56
Show Gist options
  • Save Gerrit0/1c7445ec5a23c656a86e0cc21c790941 to your computer and use it in GitHub Desktop.
Save Gerrit0/1c7445ec5a23c656a86e0cc21c790941 to your computer and use it in GitHub Desktop.
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