繁体   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