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 .csproj
file:
<ItemGroup>
<Content Include="Models\Model.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>Model.ts</LastGenOutput>
</Content>
</ItemGroup>
.njsproj
, so this needs to live in your .csproj
Write your T4 Templates to write the output that you want.
.tt
file in Visual Studio and choosing Run Custom Tool
This is great, but requiring manual intervention for code generation is so 2019.
Install NuGet package Mono.TextTransform
Run your T4 Text Transforms after the C# code builds:
PostBuildEvent
BackEnd.csproj
:<PropertyGroup>
<PostBuildEvent>"$(SolutionDir)packages\Mono.TextTransform.1.0.0\tools\TextTransform.exe" "$(ProjectDir)Models\Model.tt" -a=outDir!"$(TargetDir)$(ConfigurationName)\"</PostBuildEvent>
</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 .csproj
file.
Further reading...