首页 > 解决方案 > T4 模板在构建期间未转换

问题描述

我做了什么

我试图将我的 T4 模板编译成 ac# 文件。

我从微软尝试过的:在构建过程中调用文本转换

通过添加我的 .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 Studio\2019\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.       

但是ModelTemplateTest.tt 被编译成:

namespace MyNamespace 
{
    public class Model
    {

    }
}

我如何调用TextTemplatingFilePreprocessor我的构建?

标签: c#.netvisual-studiotemplatest4

解决方案


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


推荐阅读