How to include package reference files in your nuget
This is a particularly common scenario if you're developing MSBuild tasks or Roslyn code analyzers: all the dependencies you use in your task, analyzer or source generator, need to be included in your nuget package too, alongside your project primary output (i.e. under the properanalyzer, tools or build
folders). A very convenient way (if not comprehensive, since it won't include with transitive dependencies) to do so is by annotating your PackageReference
themselves, like:
The Pack
metadata value can then be used to include the assets in the package with the following target:
Quite a few things to note in the above target that aren't too obvious:
We use the
RuntimeCopyLocalItems
item group which is resolved byResolvePackageAssets
and contains the stuff that is needed for the dependency to run (i.e. the actual binaries, not reference assemblies, if it includes them).We use Inputs/Outputs on it so we can batch by
%(RuntimeCopyLocalItems.NuGetPackageId)
: this makes processing simpler inside the target, since we'll be dealing with a singleNuGetPackageId
for each batch, regardless of how manyRuntimeCopyLocalItems
there are.We next get that package ID as a property, and find the
@(PackageReference)
with that ID, to determine if it needs to be packed or not.Note we use property syntax next since we know there can be at most one such
@(PackageReferenceDependency)
, in which case we'd get either an empty value ortrue
for%(Pack)
.If we have to pack, we include all the
@(RuntimeCopyLocalItems)
(in the current batch, MSBuild does this for us for free thanks to the Inputs/Outputs) and use as the package path the same as what the primary project output will use. These are added directly as_PackageFiles
which is what the SDK-style projectPack
uses.We update the items metadata so they are also flagged as copy-local
Finally, the
ResolvedFileToPublish
is useful when creating dotnet tools, since packing those is slightly different and includes a publish operation.
Last updated