如何 运行 构建时在 Blazor 项目中使用 T4 模板

How to run T4 template in Blazor project on build

我有一个 Blazor 项目,其中包含我编写的用于自动构建一些代码的 T4 模板。它在 Visual Studio 中运行良好,但我必须修改并保存模板以再次将其设置为 运行(如记录和预期)。

我也想在构建项目时运行模板,所以不是VS 运行宁模板,它必须是MSBuild。我浏览了很多关于该主题的文章,看起来我必须重新导入默认目标,as explained here

我将以下内容添加到我的 .csproj 文件的顶部,这就是事情变得糟糕的时候:

<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />

这是我遇到的错误:

The TargetFramework value 'netstandard2.1' was not recognized. It may be misspelled. If not, then the TargetFrameworkIdentifier and/or TargetFrameworkVersion properties must be specified explicitly. TestProject C:\Program Files\dotnet\sdk.1.401\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets 93

完整的 .csproj 文件:

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

    <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />
    
    <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <RazorLangVersion>3.0</RazorLangVersion>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1" />
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.1" PrivateAssets="all" />
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.1" PrivateAssets="all" />
        <PackageReference Include="System.Net.Http.Json" Version="3.2.0" />
    </ItemGroup>

</Project>

我missing/doing哪里错了?

您应该注意文章中的信息:

Fortunately, there’s a workaround: you can import the default targets file explicitly, and import the text templating targets after that:

解决方案

您应该在 netstandard 2.1 节点之后导入这些目标。

在我身边,我用这些:

<Project Sdk="Microsoft.NET.Sdk.Web">
        
           <PropertyGroup>
               <TargetFramework>netstandard2.1</TargetFramework>
               <RazorLangVersion>3.0</RazorLangVersion>
           </PropertyGroup>
       
       
         <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk.Web" />
         <Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets"/>
       
           <ItemGroup>
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1"/>
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build"
   Version="3.2.1" PrivateAssets="all" />
               <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer"
   Version="3.2.1" PrivateAssets="all" />
               <PackageReference Include="System.Net.Http.Json" Version="3.2.0"/>
           </ItemGroup>
       
 </Project>

然后,