如何从 Class 库 NuGet 包中排除包?

How to exclude a package from a Class Library NuGet package?

我有一个 .NET Standard class 库项目,它将被构建到 NuGet 包中。我已经安装了 docfx.console 包,这样我每次构建时都可以生成一个文档网站。

现在,当另一个项目安装我的库的 NuGet 包时,docfx.console NuGet 包也会安装 - 我不想要。

在 Package 下的项目属性中,我选择了 Generate NuGet package on build。当我构建它时,这会自动为我的库生成 NuGet 包。但是在此选项卡中,我看不到任何可以配置以排除任何包的地方。

所以为了排除docfx.console包,我创建了一个包含以下内容的.nuspec文件:

<?xml version="1.0" encoding="utf-8" ?>

<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <!-- Required elements-->
    <id>My.Library</id>
    <version>1.0.1</version>
    <description>My Library's project dscription.</description>
    <authors>Me</authors>
    <copyright>My Copyright (c)</copyright>

    <!-- Optional elements -->
    <dependencies>
      <dependency id="docfx.console" version="2.36.1" exclude="build" />
    </dependencies>
    <!-- ... -->
  </metadata>
  <!-- Optional 'files' node -->
</package>

但它不起作用。如何更正它以在构建 NuGet 包时排除 docfx.console 包?

或者,有没有其他方法可以从 NuGet 包中排除 docfx.console 包?

How to exclude a package from a Class Library NuGet package?

根据NuGet官方文档Controlling dependency assets:

You might be using a dependency purely as a development harness and might not want to expose that to projects that will consume your package. In this scenario, you can use the PrivateAssets metadata to control this behavior.

<ItemGroup>
    <!-- ... -->

    <PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0">
        <PrivateAssets>all</PrivateAssets>
    </PackageReference>

    <!-- ... -->
</ItemGroup>

因此,正如 UserName 评论的那样,您可以在项目中将 <PrivateAssets>all</PrivateAssets> 添加到 docfx.consolePackageReference

要完成这个,编辑你的项目文件.csproj如下:

  <ItemGroup>
    <PackageReference Include="docfx.console" Version="2.36.2" PrivateAssets="All" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="docfx.console" Version="2.36.2">
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

如果您正在使用 .nuspec 文件,您应该在 .nuspec 文件中移动以下依赖信息:

<dependencies>
  <dependency id="docfx.console" version="2.36.1" />
</dependencies>