【问题标题】:Using Pre and Post build actions in dotnet core csproj files在 dotnet core csproj 文件中使用 Pre 和 Post 构建操作
【发布时间】:2017-10-22 00:51:52
【问题描述】:

我是 .NET Core 新手,我正在尝试在我的 csproj 文件中设置预构建操作。根据[1],我们可以使用 Target 元素来指定预构建步骤,如下所示:

<Target Name="MyPreCompileTarget" BeforeTargets="Build">
        <Exec Command="generateCode.cmd"/>
</Target>

但是,MSBuild 工具似乎没有拾取此元素。我完整的 csproj 文件如下:

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

    <PropertyGroup>
        <TargetFramework>netcoreapp1.1</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <Folder Include="wwwroot\"/>
    </ItemGroup>
    

    <Target Name="MyPreCompileTarget" BeforeTargets="Build">
        <Exec Command="echo meow meow"/>
    </Target>

    <ItemGroup>
        <PackageReference Include="FluentValidation.AspNetCore" Version="7.0.0"/>
        <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2"/>
        <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3"/>
        <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.0.3"/>
        <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2"/>
    </ItemGroup>

    <ItemGroup>
        <ProjectReference Include="..\my-lib\<my-lib>.csproj"/>
    </ItemGroup>

</Project>

参考文献

[1] - https://docs.microsoft.com/en-us/dotnet/articles/core/tools/project-json-to-csproj#the-csproj-format

【问题讨论】:

    标签: msbuild .net-core


    【解决方案1】:

    echo 在这种情况下是命令 shell (cmd.exe) 的内置函数,因此它不起作用。

    如果你只使用例如generateCode,msbuild 还将根据您运行的平台查找与该名称匹配的 .bat 或 .sh 文件。

    您可以使用/v:diag 运行dotnet build 命令以获得完整的诊断输出。

    您还可以通过在目标中添加这样的任务来验证您的目标是否实际运行:

    <Message Importance="high" Text="Test Message" />
    

    另外,由于echo 在 mac 上可用,所以当我在 Mac 上运行时,您的项目文件会达到预期效果:

    MacBook-Pro:footest martin$ dotnet build
    Microsoft (R) Build Engine version 15.3.234.47922 for .NET Core
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      footest -> /Users/martin/tmp/footest/bin/Debug/netcoreapp1.1/footest.dll
      meow meow
    
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    

    【讨论】:

    • 谢谢马丁。 Message 元素和诊断命令帮助我缩小了问题范围。事实证明,BeforeTargets="Build" 在构建步骤之前没有执行任务,而是我不得不使用“BeforeBuild”。在我的设置中,由于 ProjectReference 指向不存在的自定义库,构建失败(我试图使用预构建操作来克隆库存储库)。我在这个 SO 问题中找到了解决方案:stackoverflow.com/questions/27986147/… .我想我的问题可能是重复的问题。
    • 如果您使用 git clone 另一个 repo 的步骤,它可能无论如何都不起作用,因为您需要进行额外的 dotnet restore 调用才能使事情正常工作。将其作为构建前事件进行可能会导致麻烦。
    • 对于这些场景,您通常最好在自己的项目文件中编写脚本 (gist.github.com/dasMulli/69f5303aa79a8cd4060e44891c90fd2d)
    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2021-07-01
    • 2019-06-09
    • 1970-01-01
    • 2017-06-27
    • 2015-08-09
    相关资源
    最近更新 更多