如何不打包 C# 源代码生成器而不将其上传到 NuGet?

问题描述

我创建了一个类库并将其上传到 NuGet.org。 类库使用 C# 源代码生成生成重复代码(例如使用值元组方法)。

类库在 NuGet.org 上过着幸福的生活,但是,不知何故,源代码生成器项目也被打包上传了,这不是我想要的......

如何阻止生成器项目上传到 NuGet?


类库的.csproj

<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <TargetFramework>net5.0</TargetFramework>
   </PropertyGroup>

   <PropertyGroup>
      <!-- Version,Authors,Description and other NuGet package info abbreviated here. -->
   </PropertyGroup>

   <ItemGroup>
      <ProjectReference
         Include="..\MyLib.sourceGenerators\MyLib.sourceGenerators.csproj"
         OutputItemType="Analyzer"
         ReferenceOutputAssembly="false"/>
   </ItemGroup>
</Project>

生成器的.csproj

<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <TargetFramework>netstandard2.0</TargetFramework>
      <LangVersion>9.0</LangVersion>
   </PropertyGroup>

   <ItemGroup>
      <packagereference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0"/>
      <packagereference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2">
         <PrivateAssets>all</PrivateAssets>
         <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      </packagereference>
   </ItemGroup>
</Project>

解决方法

<IsPackable>false</IsPackable> 添加到源生成器项目的 .csproj 似乎会阻止生成 NuGet 包,类似于单元测试项目。

<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <TargetFramework>netstandard2.0</TargetFramework>
      <LangVersion>9.0</LangVersion>
      <IsPackable>false</IsPackable> <!-- HERE -->
   </PropertyGroup>

   <ItemGroup>
      <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0"/>
      <!-- ... -->