Search code examples
angularangular-cliangular-cdkangular-compilerangular-devkit

Preprocessing Angular templates before compiling


I'm trying to plug into the compile step and modify the AST to amend a data attribute to DOM elements (HTML templates).

This is to inject information into the DOM at compile time without modifying the source code. The idea is to have the preprocessor run as a build step every time the project is built to do the injection.

Is there an official preprocessing step for angular? Has anyone tried something similar?

I'm able to do this easily for Svelte, React, and Nextjs but am having a lot of trouble with Angular.

Things I've tried:

  • Schematics which is not appropriate because it modifies the source code and is more for building
  • ngx-ast-transform I got close with this but the AST returned is Typescript, not Angular hence I could not access the templates
  • Webpack loaders which I'm still experimenting with. It does not explicly give the AST that Angular works with but I'm trying to use Angular compiler API to modify the loaded source code

My expectations are to be able to modify the AST during the preprocessing step similar to Svelte preprocess step or SWC plugins but I have not found an official way with Angular.


Solution

  • The solution I went with is a custom builder that is a wrapper around the base builder similar to @angular-builders/custom-webpack. The builder has a preprocess step in which iterates through template files, save a snapshot of it and transform it to add the attributes I want. Then it calls the base builder then run a postprocess to restore the template files afterwards.

    I tried using @angular/compiler but ended up going with a base HTML parser (parse5-case-sensitive) instead because @angular/compiler doesn't let you serialize the result back easily. For production, I will try again with the official compiler but their API is not public. The weakness of this is that this is not good for long-running dev server because the templates get overwritten after the build is finished. But works fine for production build.

    Here is a useful thread if you want other options: https://www.reddit.com/r/angular/comments/1cv1hda/comment/l4oai85/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button