April 9, 2020
T4 templates can be used to auto-generate code, such as creating TypeScript types from C# class/enums. Remove the manual step by automatically running your templates as part of the build process.
In Visual Studio, a T4 text template is a mixture of text blocks and control logic that can generate a text file. The control logic is written as fragments of program code in Visual C# or Visual Basic.
The generated file can be text of any kind, such as a web page, or a resource file, or program source code in any language.
Read more here background here:
Add reference to your T4 templates in your
xml1<ItemGroup>2 <Content Include="Models\Model.tt">3 <Generator>TextTemplatingFileGenerator</Generator>4 <LastGenOutput>Model.ts</LastGenOutput>5 </Content>6</ItemGroup>
.njsproj, so this needs to live in your
Write your T4 Templates to write the output that you want.
.ttfile in Visual Studio and choosing
Run Custom Tool
This is great, but requiring manual intervention for code generation is so 2019.
Install NuGet package
Run your T4 Text Transforms after the C# code builds:
xml1<PropertyGroup>2 <PostBuildEvent>"$(SolutionDir)packages\Mono.TextTransform.1.0.0\tools\TextTransform.exe" "$(ProjectDir)Models\Model.tt" -a=outDir!"$(TargetDir)$(ConfigurationName)\"</PostBuildEvent>3</PropertyGroup>
Now when you build, your generated output will be re-generated after the build succeeds. Whew! 😅
If you need to run your T4 template before the build, such as for T4 MVC, you'll want to use a
<PreBuildEvent> instead of the
<PostBuildEvent> above in your