MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板

MSBuild support for T4 templates in Visual Studio 2017 RTM

在 Visual Studio 2015 年,我使用了 NuGet 包 Unofficial.Microsoft.VisualStudio.TextTemplating.14.0.0,它允许我在构建项目时直接从 MSBuild 转换 T4 模板。

然而,在 Visual Studio 2017 RTM 中,这会破坏构建并显示以下消息:

An Exception was thrown while running the transformation code. The process cannot continue. The following Exception was thrown: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. File name: 'Microsoft.CodeAnalysis, Version=1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

这是由此包中的文件 Unofficial.Microsoft.VisualStudio.TextTemplating.targets(396,5) 引起的。

我的猜测是错误来自于由于环境不匹配而尝试使用 VS 2017 构建中的这些目标,但我不知道如何追踪确切的问题。我还没有看到 v15 的更新包。

如何从适用于 VS 2017 的 MSBuild 执行 T4 转换?是否会有来自 NuGet 的新包在某个时候使用,或者这将不再受支持?

我找到了正确的解决方案。

事实证明,T4 SDK 现在作为 Visual Studio 2017 的一部分包含在内(而不是像过去那样作为单独的建模 SDK 的一部分),但您必须通过 Visual Studio extension development VS2017 安装程序中的工具集(文本模板转换功能)。

安装后,您可以通过将相关目标导入 MSBuild 项目来使用 MSBuild 转换模板:

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <TransformOnBuild>True</TransformOnBuild>
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
</PropertyGroup>

<!-- add AFTER import for $(MSBuildToolsPath)\Microsoft.CSharp.targets -->
<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

这解决了我的问题,也消除了对单独的非官方 NuGet 包的需要。

我有一个类似的问题,我在 Visual Studio Team Service 上的托管代理没有生成模板输出,因此破坏了我的构建服务器,因为它缺少生成的 CS 文件。

在我的开发机器上从 Visual Studio 2015 构建时,CS 模板输出生成得很好。

查看各种解决方案,例如上面的解决方案,我清楚地知道更权宜之计的解决方法是 将生成的文件提交到我的源代码控制系统。这具有额外的优势,我可以对输出中的任何更改进行代码审查,而不仅仅是模板。

我遇到了类似的问题。我的 T4 不会在生成时生成,但会在保存时生成。这很奇怪,因为我没有收到错误,但在阅读@Sam 的回答后,我发现我的 VS 安装有问题。我是对的。 VS 2017 15.9.4 安装在它自己的安装目录中,但不会将工具复制到 VSToolsPath 文件夹。相反,它只是让他们留在原地。所以,对我来说,正确的解决方案是使用这个 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(VsInstallRoot)\MSBuild\Microsoft\VisualStudio\v15.0\TextTemplating\Microsoft.TextTemplating.targets" />

T4Executer 执行此操作,您可以设置在构建之前或之后执行哪些模板,或者设置哪些模板不应 运行 在构建时执行。 VS2017-19