T4 templates in F# project

54 Views Asked by At

I have been using T4 templates in C# projects in Visual Studio. Now I am trying to get some generation in an F# project, using mono t4.

I have attempted to adapt the examples I found (for example TextTemplating target in a .Net Core project), but I have not been successful, as in "Nothing is generated".

This is the project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
      <TargetFramework>net4.8</TargetFramework>
      <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

  <ItemGroup>
    <None Include="Template.tt" />
    <Compile Include="**.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Mono.TextTemplating" Version="2.3.1" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Update="FSharp.Core" Version="7.0.200" />
  </ItemGroup>  

</Project>

It should be possible (I hope), to add some entries manually in the .fsproj file to force msbuild to run the transformation of the .tt file (in C# it all occurs automatically), however I don't know:

  • Whether it is possible.
  • How to do it.

Help please.

1

There are 1 best solutions below

0
Tim Maes On

Maybe you can try something like this:

<Project Sdk="Microsoft.NET.Sdk">

  <!-- ... other configuration ... -->

  <Target Name="TransformTemplates" BeforeTargets="BeforeBuild">
    <Exec Command="t4 -o $(IntermediateOutputPath)\GeneratedFile.cs Template.tt" />
  </Target>

  <ItemGroup>
    <Compile Include="$(IntermediateOutputPath)\GeneratedFile.cs" />
  </ItemGroup>

</Project>

TransformTemplates is a custom target that runs before the build

The Exec task runs the t4 command to transform Template.tt into a C# file.

The generated C# file should included in the compilation.

Related Questions in F#