Automatic TypeScript Model Generation With TDS
New Tech, New Problems
Building stable Sitecore sites with NextJS is best done with TypeScript (not plain JS). Front end developers (FEDs) simply need the IDE feedback that TypeScript provides; particularly around null pointers. In my experience, even if you tell FEDs that there are always cases in which almost any field or item or value can be null, there's just too much to remember. TypeScript is a great way to help FEDs remember.
The future landscape of content serialization and model generation is a bit unclear at the moment. The transition to headless and JS feels like a step backwards in some ways because I haven't yet seen a compelling way to generate TypeScript models from Sitecore. For example, serialization is moving towards Sitecore Content Serialization, but it does not yet support model generation.
This is a problem because many of our sites will have hundreds of templates and perhaps even thousands of fields. Manually creating TypeScript models for all of these is too slow.
"What do you need, Neo?"
"Models. Lots of Models."
TDS Model Generation
One of the great features of TDS is that it supports automatic model generation out of the box. It does so using T4 Text Templates (.tt files). T4 is a code generation tool that is built into Visual Studio. It's a bit tedious to work with, but it's a great way to generate code from other code.
With the click of a single button, or the syncing of a single item, TDS will generate for us a glorious monolithic .cs file containing all of our models:
From there, ORM tools such as GlassMapper can be used to map Sitecore items to these models.
I wanted a way to hook into the existing TDS model generation process in a way that was fully automatic so developers wouldn't forget to sync. I also wanted to write directly to a .ts file.
Keep in mind that the
templates.tt file runs once per template, but I haven't yet found a OOTB way to track where we are in the loop (start and end is crucial here).
If you don't already have TDS code generation set up, be sure to check out the TDS guide on code generation.
Make sure that the top of your common.tt file looks like this:
Further down, add this:
How to Call The Code
In your templates.tt file, ensure the header of your file contains:
If you've set up TDS code generation properly, you will already have plenty of logic in this file. At the bottom of the file, here is how you would make the call to the method we set up in common.tt:
The output model.ts file will look something like this:
There you have it; a viable method for automating TS model generation. Now that the ground has been broken, there are many ways that this can be customized / optimized.
There are also some creative things you can do beyond this. For example, you can run command line commands from .tt files in case you want to do any other kind of post processing after the models have been generated.
The solution below is incomplete, but it's a start: