簡體   English   中英

如何在構建時有條件地編譯 NuGet 包?

[英]How to conditionally compile a NuGet package on build?

我在項目中使用 NuGet 包。 有沒有辦法隔離或忽略該 NuGet 包並使用編譯開關或宏使用另一個 NuGet 包?

目的:此 NuGet 包按開發人員授權,因此目的是在開發過程中將其與其他開發人員斷開連接。

我查看了 myproject.csproj

...
<ItemGroup>
    <PackageReference Include="nugetPackage2Exclude" Version="1.0.0.0">
        <ExcludeAssets>none</ExcludeAssets>
    </PackageReference>
...

但是,我無法使用編譯開關或宏使其工作。

經過一番折騰。 這是最終滿足我所有要求的解決方案。 它有點長,我已經添加了與這個問題相關的所有發現。

在開始實施之前,這是我的設置 #(.NET 6.0, C# 10, WPF Project, VS2022)

涉及的步驟!

  1. 編譯開關的聲明
  2. 用於編譯/忽略 Nuget 包的預構建條件開關
  3. XAML 文件中的上下文切換。
  4. 編譯開關以隔離 C# 文件中的包。

Step1 :聲明編譯開關(NUGET_ENABLE)

項目 -> 屬性 -> 條件編譯符號

$(DefineConstants);NUGET_ENABLE

(注意:不能為 NUGET_ENABLE 分配值,必須重命名或刪除 NUGET_ENABLE 才能刪除此 NuGet 用法。)

Step2 : Prebuild 用於編譯/忽略 Nuget 包的條件開關

打開myproject.csproj (項目文件)。 使用正則表達式從 $(DefineConstants) 中查找特定的編譯開關,如果 NUGET_ENABLE 存在,則編譯 NuGet 包。

(參考: MS Docs

    <Choose>
    <When Condition="$([System.Text.RegularExpressions.Regex]::IsMatch($(DefineConstants), '^(.*;)*NUGET_ENABLE(;.*)*$'))">
        <!-- When NUGET_ENABLE is defined. -->
        <ItemGroup>
            <PackageReference Include="nugetPackage2Exclude" Version=""/>
        </ItemGroup>
    </When>
    </Choose>

Step3 : XAML 文件中的上下文切換

公平警告!<mc:AlternateContent>標簽可能會阻止在 VS 或 Blend 中加載設計預覽窗口(Xaml Designer)。

(參考: 這個問題

Step3a :編輯程序集文件以添加 XAML 開關

#if NUGET_ENABLE 
[assembly: XmlnsDefinition("nuget_enable", "NameSpace")]
#endif // NUGET_ENABLE

Step3b :添加 XAML 文件頭

    ...
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:nuget="http://schemas.nugetPackage2Exclude.etc/"
     xmlns:nugetEnabled="nuget_enable"
    ...
     mc:Ignorable="d nuget" // d is optional!
    ...

Step3c :添加 XAML 上下文切換

    <mc:AlternateContent>
        <mc:Choice Requires="nugetEnabled">
                <!--<code calling the nuget>-->
        </mc:Choice>
        <mc:Fallback>
        
        </mc:Fallback>
    </mc:AlternateContent>

Step4 :編譯開關以隔離C#文件中的包。

#if NUGET_ENABLE 
// Code
#endif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM