0

I have a custom TypeScript watcher that looks something like:

const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic)
typescript.createWatchProgram(compilerHost)

I want to hook up a custom transformer that is used when the watcher compiles my .ts files. If I was doing a one-time compile, I would do something like this, supplying the transformer as the last parameter.

const program = typescript.createProgram(config.fileNames, config.options)
const emitResult = program.emit(undefined, undefined, undefined, undefined, { before: [ transformer(program) ] })

However, I cannot find any way to add the transformer to either the compiler host or the watch program creation.

How can I add a custom transformer to a watch compiler host?

One way to do it in theory would be to supply a custom CreateProgram to the createWatchCompilerHost that has the emit function on the returned objects overriden with my custom transformer. I'm unclear on how realistic that path would be though and am looking for a better option.

Micah Zoltu
  • 6,764
  • 5
  • 44
  • 72

1 Answers1

0

The following is functional (for my case), but I'm not a big fan of it. Would love to see some better answers.

const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic)
const originalAfterProgramCreate = compilerHost.afterProgramCreate
compilerHost.afterProgramCreate = builderProgram => {
    const originalEmit = builderProgram.emit
    builderProgram.emit = (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers): typescript.EmitResult => {
        const transformers = customTransformers || { before: [] }
        if (!transformers.before) transformers.before = []
        transformers.before.push(myTransformer(builderProgram.getProgram()))
        return originalEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, transformers)
    }
    if (originalAfterProgramCreate) originalAfterProgramCreate(builderProgram)
}
typescript.createWatchProgram(compilerHost)
Micah Zoltu
  • 6,764
  • 5
  • 44
  • 72