Skip to main content

Source only NuGet packages

By Betim Beja ·

In the .NET ecosystem NuGet packages are the de facto standard for sharing reusable parts of code and tools. You can share pre-compiled assemblies, content, build targets tools and more. You can read about the conventions that are used here.

In this article, we will focus on source only NuGet packages, which contain source code and content which will be added to the project that references the NuGet package.

The most used approach until now has been using the \content folder of a NuGet package to distribute the source code and other contents. But this approach has different drawbacks. For example the files are literally copied on the project root, which means that we have to commit "generated" code in our repository. Also having the files in your project means that you can modify those files, so you risk having conflicts regarding the "version" of your files. Also we are distributing those files so that they can be part of a MSBuild project, but we don't have much control on how these artifacts will be used by the consuming project, that means there is an extra effort to configure the project.

AlbanianXrm would like to present an alternative approach to creating source only NuGet packages which avoids all the drawbacks we explained earlier for the \content based packages.

As you can read in the NuGet documentation here, placing files in the form <package_id>.targets or <package_id>.props within the \build folder, when you install the package you get two <Import> elements in the project file one pointing to the .targets and one pointing to the .props file.

Other files put on the \build folder will get ignored by this automatic import, but what we can do is use the $(MSBuildThisFileDirectory) property in the .targets file to import our assets in the project. There are various ways to include the files in the project, AlbanianXrm offers an OpenSource example here, using a shared project.

A video demonstration has been uploaded on YouTube

If you need consulting about this or other activities contact us.