为了在
dotnet build
时支持构建T4模板,您需要使用
自定义文本模板主机
,它已经存在于.NET Core中(
https://github.com/atifaziz/t5)。为了包含它,请在任何
ItemGroup
中添加以下元素:
<DotNetCliToolReference Include="T5.TextTransform.Tool" Version="1.1.0-*" />
。
由于Visual Studio已经有了自己的
文本模板主机
实现,您添加的元素应该只针对.NET Core进行条件判断。例如:
<ItemGroup Condition="'$(MSBuildRuntimeType)'=='Core'">
<DotNetCliToolReference Include="T5.TextTransform.Tool" Version="1.1.0-*" />
</ItemGroup>
同时,您应该将 Visual Studio 的文本模板主机的设置从 .NET Core 中条件化掉,像这样:
Condition="'$(MSBuildRuntimeType)'=='Full'"
。
在导入
Microsoft.TextTemplating.targets
之前,您还应该添加
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" Condition="'$(MSBuildRuntimeType)'=='Full'" />
,使一切在 Visual Studio 中使用 .NET Core
csproj
正常运行。
如果您需要能够清理所有生成的代码,您应该将模板从
*.tt
重命名为
*.Generated.tt
,所有代码将在
*.Generated.cs
下生成,并且可以在
dotnet clean
操作中过滤这些文件。
以下是在您的
csproj
中完整示例:
<ItemGroup Condition="'$(MSBuildRuntimeType)'=='Core'">
<DotNetCliToolReference Include="T5.TextTransform.Tool" Version="1.1.0-*" />
<TextTemplate Include="**\*.Generated.tt" />
<Generated Include="**\*.Generated.cs" />
</ItemGroup>
<Target Name="TextTemplateTransform" BeforeTargets="BeforeBuild" Condition="'$(MSBuildRuntimeType)'=='Core'">
<ItemGroup>
<Compile Remove="**\*.cs" />
</ItemGroup>
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet tt %(TextTemplate.Identity)" />
<ItemGroup>
<Compile Include="**\*.cs" />
</ItemGroup>
</Target>
<Target Name="TextTemplateClean" AfterTargets="Clean">
<Delete Files="@(Generated)" />
</Target>
<PropertyGroup Condition="'$(MSBuildRuntimeType)'=='Full'">
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<TransformOnBuild>true</TransformOnBuild>
<OverwriteReadOnlyOutputFiles>true</OverwriteReadOnlyOutputFiles>
<TransformOutOfDateOnly>false</TransformOutOfDateOnly>
</PropertyGroup>
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" Condition="'$(MSBuildRuntimeType)'=='Full'" />
<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" Condition="'$(MSBuildRuntimeType)'=='Full'" />
如果您不想重命名模板文件并且不需要清理它们,那么请将以下内容替换为:
<TextTemplate Include="**\*.Generated.tt" />
<Generated Include="**\*.Generated.cs" />
使用:
<TextTemplate Include="**\*.tt" />
并删除:
<Target Name="TextTemplateClean" AfterTargets="Clean">
<Delete Files="@(Generated)" />
</Target>
更多信息请参见:
如何在dotnet build
上设置代码生成:
https://notquitepure.info/2018/12/12/T4-Templates-at-Build-Time-With-Dotnet-Core/
如何为Visual Studio和.NET Core csproj
构建设置代码生成:
https://thomaslevesque.com/2017/11/13/transform-t4-templates-as-part-of-the-build-and-pass-variables-from-the-project/
从单个T4模板生成多个文件的完整示例:
https://github.com/Konard/T4GenericsExample
更新:
GitHub.com/Mono/T4 更好。