Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created April 30, 2025 07:31
Show Gist options
  • Save souporserious/cbb955e3c299241f6f8ca3d5c8824665 to your computer and use it in GitHub Desktop.
Save souporserious/cbb955e3c299241f6f8ca3d5c8824665 to your computer and use it in GitHub Desktop.
import type { Project, ts } from 'ts-morph'
import * as tsMorph from 'ts-morph'
const printerCache = new WeakMap<Project, ts.Printer>()
const LineFeed = tsMorph.ts.NewLineKind.LineFeed
/** Get a ts.Printer configured to match the project’s `compilerOptions`. */
export function getPrinter(
project: Project,
overrides?: Partial<ts.PrinterOptions>
): ts.Printer {
let printer = printerCache.get(project)
if (printer) return printer
const options = project.getCompilerOptions()
printer = tsMorph.ts.createPrinter({
removeComments: overrides?.removeComments ?? options.removeComments ?? true,
newLine: overrides?.newLine ?? options.newLine ?? LineFeed,
noEmitHelpers: overrides?.noEmitHelpers ?? options.noEmitHelpers ?? false,
omitTrailingSemicolon: overrides?.omitTrailingSemicolon ?? false,
})
printerCache.set(project, printer)
return printer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment