T4 模板在构建期间未转换

T4 templates not transformed during build

我做了什么

我尝试将我的 T4 模板编译成 c# 文件。

我从 Microsoft: Invoke text transformation in the build process

中尝试过的

通过在我的 .csproj 文件中添加:

  <Import Project="TextTemplating\Microsoft.TextTemplating.targets" />
  <PropertyGroup>
    <TransformOnBuild>true</TransformOnBuild>
    <OverwriteReadOnlyOutputFiles>true</OverwriteReadOnlyOutputFiles>
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
  </PropertyGroup>
  <ItemGroup>
    <T4ParameterValues Include="ProjectDir">
      <Value>$(ProjectDir)</Value>
      <Visible>false</Visible>
    </T4ParameterValues>
  </ItemGroup>

TextTemplating 是一个包含来自我的编辑器的 TextTemplating 文件的目录,位于: C:\Program Files (x86)\Microsoft Visual Studio19\Enterprise\msbuild\Microsoft\VisualStudio\v16.0\TextTemplating

模板

基础模板(名为ModelTemplate.tt):

<#@ template language="C#" #>
<#@ parameter name="ClassName" type="System.String"#>
<#@ parameter name="Namespace" type="System.String"#>

namespace <#= Namespace #> 
{
    public class <#= ClassName #>
    {

    }
}

最后是用于测试 ModelTemplate.tt 的模板(名为 ModelTemplateTest.tt):

<#@ template debug="false" language="C#" #>
<#@ output extension=".cs" #>
<#
    _ClassNameField = "Model";
    _NamespaceField = "MyNamespace";
#>
<#@ include file="$(ProjectDir)\Templates\ModelTemplate.tt"#>

构建的输出

A custom tool 'TextTemplatingFilePreprocessor' is associated with file 'Templates\ModelTemplate.tt', but the output of the custom tool was not found in the project.  You may try re-running the custom tool by right-clicking on the file in the Solution Explorer and choosing Run Custom Tool.       

BUT将ModelTemplateTest.tt编译成:

namespace MyNamespace 
{
    public class Model
    {

    }
}

如何在我的构建中调用 TextTemplatingFilePreprocessor

T4Executer 可能是一个解决方案,它是一个 VS 扩展,允许您在项目构建时触发特定 T4 文件的执行。

解决方案(使用Visual Studio Enterprise 2019) 是在.csproj 文件中导入$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v16.0\TextTemplating\Microsoft.TextTemplating.targets,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <PropertyGroup>
    <TransformOnBuild>true</TransformOnBuild>
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TextTemplating\Microsoft.TextTemplating.targets" />
</Project>

相关 Whosebug 线程:Product of build-time T4 transformation is used only in the next build