How can I use BeforeBuild and AfterBuild objects using Visual Studio 2017?

After switching to csproj to use Visual Studio 2017 and Microsoft.NET.Sdk, my BeforeBuild and AfterBuild targets no longer work. My file is as follows:

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

  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

  <!-- my targets that don't run -->
  <Target Name="BeforeBuild">
      <Message Text="Should run before build" Importance="High" />
  </Target>

  <Target Name="AfterBuild">
      <Message Text="Should run after build" Importance="High" />
  </Target>

</Project>
+11
source share
3 answers

A related issue with MSBuild git recommends not using BeforeBuild / AfterBuild as future task names, instead assign the name to the task accordingly and associate it with the goals

<Project Sdk="Microsoft.NET.Sdk"> 
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

  <!-- Instead of BeforeBuild target -->
  <Target Name="MyCustomTask" BeforeTargets="CoreBuild" >
      <Message Text="Should run before build" Importance="High" />
  </Target>

  <!-- Replaces AfterBuild target -->
  <Target Name="AnotherCustomTarget" AfterTargets="CoreCompile">
      <Message Text="Should run after build" Importance="High" />
  </Target>    
</Project>

idiomatic VS 2017, /, .

+13

Project Sdk="Microsoft.NET.Sdk", " ". , Microsoft.NET.Sdk/Sdk.targets csproj, "BeforeBuild" "AfterBuild".

, , .

<Project>

  <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />

  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

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

  <!-- add your custom targets after Sdk.targets is imported -->
  <Target Name="BeforeBuild">
      <Message Text="Should run before build" Importance="High" />
  </Target>

  <Target Name="AfterBuild">
      <Message Text="Should run after build" Importance="High" />
  </Target>

</Project>
+7

In the already mentioned release of GitHub, Rainer Sigwald offers a much shorter and more elegant solution:

<Target Name="CustomBeforeBuild" BeforeTargets="BeforeBuild"> ... </Target>
<Target Name="CustomAfterBuild" AfterTargets="AfterBuild"> ... </Target>

It looks weird, but it works great.

0
source

Source: https://habr.com/ru/post/1017186/


All Articles