简体   繁体   中英

DefineConstant in NuGet package's props based on the target platform

I'm building a multi-target NuGet package and I want it to provide a compile constant for the consumer:

<TargetFrameworks>Xamarin.Mac20;netstandard2.0;uap10.0.17763</TargetFrameworks>

I want a certain feature to be only available for two of this targets. To do so I'm defining a custom constant:

<PropertyGroup Condition="$(TargetFramework.StartsWith('uap10.0.17763')) Or $(TargetFramework.StartsWith('Xamarin.Mac'))">
    <DefineConstants>$(DefineConstants);FEATURE_AVAILABLE</DefineConstants>
</PropertyGroup>

Now I want not only to use this constant in my current assembly I want to create a package from, but also in the consumer project. To achieve that I created a Common.props file and included it into the package:

<Import Project="Common.props" />
<ItemGroup>
  <None Include="Common.props" Pack="true" PackagePath="build" />
</ItemGroup>

After building I can confirm my Common.props was added to the package and I could successfully consume it in the main project.

The main project targets the same 3 platforms as the package project. Now I just want to use FEATURE_AVAILABLE imported from the package so I can utilise only the available code from the package.

The problem is it doesn't respect the platform conditions that wrap the DefineConstants instruction in my main project like if it was executed before MSBuild knows the target framework it's going to build for. If I remove the condition, the constant is available in my main project code. With the condition in place it's not.

It turned out Nuget doesn't respect Xamarin.Mac20 as a target name though dotnet itself does. When the packages are being restored, Nuget generates its own PROJECT_NAME.csproj.nuget.g.props file that includes the following line (cleaned up and sanitised):

<ImportGroup Condition=" '$(TargetFramework)' == 'xamarinmac20'">
  <Import Project="$(NuGetPackageRoot)MY_NUGET_NAME/VERSION/build/FILE.props" />
</ImportGroup>

Changing the target framework from Xamarin.Mac20 to xamarinmac20 solves the issue. I don't really want to do it for all of my dependent projects so I'll either be including the full import line manually or will find a way to configure Nuget to my needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM