Custom Typescript Transformers with Angular CLI

David Kingma
Jool Software Professionals
2 min readMar 27, 2019

--

We will be hacking on the Angular CLI build using private API’s. Keep in mind that these could break without prior notice!

The Angular CLI uses the AngularCompilerPlugin to transpile typescript. It is a webpack plugin that uses the typescript compiler together with various Typescript transformers to transpile the typescript to workable code for the browser. See this article from Alexey Zuev on how Angular uses code tranformations.

Looking for a way to add custom typescript transformations to an Angular project I found out that the ngx-build-plus project by Manfred Steyer supports plugins that allows you to add or manipulate plugins to the Webpack configuration. The plugin interface has methods for pre/post hooks and a method for the config manipulation.

Inside the webpack configuration that is passed to the config method you will find a webpack plugins array that (amongst others) will contain the AngularCompilerPlugin. The AngularCompilerPlugin has a _transformers property that contains all the typescript transformers that will be passed to the Typescript compiler.

For this example we create a dummy Typescript transformer that logs the filenames to the console.

First we need to compile the plugin, as it is written in typescript:

tsc --skipLibCheck --module umd -w

And now we can run a normal Angular CLI build with the plugin:

ng build --aot --plugin ~dist/out-tsc/ng-ts-register-transformer.js

Output looks like the following:

Console output when applying the dummy transformer

As you can see it outputs not only your sourcefiles, but also generated files like .ngfactory.ts and .ngstyle.ts files. This is due to the fact that the AOT compiler generates these files before the typescript transformers are executed. This might change when Ivy is introduced in Angular 8.0.

An example repository can be found at https://github.com/Joolnl/ng-ts-transformations.

References

--

--