Could a webpack plugin preprocess TypeScript files?

292 views Asked by At

My question is simply whether it is possible to write a webpack plugin that takes an input .ts file, alters the contents, and passes the output on to the TypeScript compiler to be processed into Javascript. I ask as I'm not too familiar with webpack plugins, and am considering further investigating that route. More context than needed follows.

I have a homegrown framework aimed at rapid app development in the HTML5 stack, that among other things does a lot of runtime type checking. I use a convention of adding /*param?:string*/ type comments after function and method params, similar to TS annotations. At runtime I have a facility which parses such comments and decorates functions and methods with info about their types and required params (so as to avoid the parsing on every call). I then dynamically inject different types of type-checking, so can check when methods or functions are called with wrong inputs, but also allows fancy "wiring" checks where for instance I'll do:

componentA.wire('fileLoaded', componentB.onFileLoaded)

This can detect at wiring time (not later when the listener is actually called) that componentA filedLoaded events do not conform to the signature of componentB.onFileLoaded.

This approach has proven quite useful in catching all sorts of problems as I build demo apps. However I recently began converting my framework code to use TypeScript, which catches a different set of issues earlier on and in some cases allows me to do more complex types.

The problem is, no one, including me, wants to annotate every function on every param twice, using inline comments and TS annotations. It's ugly, error-prone, and hinders readability which introduces more errors.

So it occurred to me, if I could pre-process TS files before they are compiled, I could have the best of both worlds, with both static typing and runtime type checking (configurable and optional, on a per component, per function, production vs. dev build bases). Simply convert all TS annotations into duplicate inline comments, add runtime code to parse these comments and inject runtime checks (I used wrapper functions to do this).

However before I go down the rabbit hole of experimenting with this I want to make sure this is something webpack plugins are meant to do. Or maybe simply loaders that can be chained? As I said I know very little about webpack internals, have used it exclusively for building apps using existing webpack tools so far.

0

There are 0 answers