How to create nuget package
How to create nuget package
Create a package using the nuget.exe CLI
Packaging begins with the compiled code (assemblies), symbols, and/or other files that you want to deliver as a package (see Overview and workflow). This process is independent from compiling or otherwise generating the files that go into the package, although you can draw from information in a project file to keep the compiled assemblies and packages in sync.
Decide which assemblies to package
Most general-purpose packages contain one or more assemblies that other developers can use in their own projects.
If your library contains COM interop assemblies, follow additional the guidelines in Create packages with COM interop assemblies.
Common optional properties:
Because the manifest is included in the package created from it, you can find any number of additional examples by examining existing packages. A good source is the global-packages folder on your computer, the location of which is returned by the following command:
You then edit the file by hand so that it describes the exact content you want in the final package.
From a convention-based working directory
The advantage to this approach is that you don’t need to specify in the manifest which files you want to include in the package (as explained later in this topic). You can simply have your build process produce the exact folder structure that goes into the package, and you can easily include other files that might not be part of a project otherwise:
The folder conventions are as follows:
Because your folder structure can contain any number of assemblies for any number of target frameworks, this method is necessary when creating packages that support multiple frameworks.
From an assembly DLL
Using this form replaces a few placeholders in the manifest with specific values from the assembly. For example, the property is set to the assembly name, and is set to the assembly version. Other properties in the manifest, however, don’t have matching values in the assembly and thus still contain placeholders.
From a Visual Studio project
.nuspec file contains tokens that are replaced at packaging time with values from the project, including references to any other packages that have already been installed.
Solution-level packages
NuGet 2.x only. Not available in NuGet 3.0+.
New file with default values
The following command creates a default manifest with placeholders, which ensures you start with the proper file structure:
Choose a unique package identifier and setting the version number
The package identifier ( element) and the version number ( element) are the two most important values in the manifest because they uniquely identify the exact code that’s contained in the package.
Best practices for the package identifier:
Best practices for the package version:
The following series of brief blog posts are also helpful to understand versioning:
Add a readme and other files
When using the convention-based working directory approach, you can place the readme.txt in the package root and other content in the content folder. No elements are necessary in the manifest.
When you include a file named readme.txt in the package root, Visual Studio displays the contents of that file as plain text immediately after installing the package directly. (Readme files are not displayed for packages installed as dependencies). For example, here’s how the readme for the HtmlAgilityPack package appears:
Include MSBuild props and targets in a package
In some cases, you might want to add custom build targets or properties in projects that consume your package, such as running a custom tool or process during build. You can learn more about MSBuild props and targets in NuGet packages
.props (such as Contoso.Utility.UsefulStuff.targets ) within the build folders of the project.
When packages are added to a project, NuGet will automatically include these props and targets.
with your specific filename:
Additional options
You can use various command-line switches with nuget pack to exclude files, override the version number in the manifest, and change the output folder, among other features. For a complete list, refer to the pack command reference.
The following options are a few that are common with Visual Studio projects:
This inclusion process is recursive, so if MyProject.csproj references projects B and C, and those projects reference D, E, and F, then files from B, C, D, E, and F are included in the package.
Test package installation
Before publishing a package, you typically want to test the process of installing a package into a project. The tests make sure that the necessarily files all end up in their correct places in the project.
You can test installations manually in Visual Studio or on the command line using the normal package installation steps.
For automated testing, the basic process is as follows:
Next Steps
You might also want to extend the capabilities of your package or otherwise support other scenarios as described in the following topics:
Finally, there are additional package types to be aware of:
Quickstart: Create and publish a NuGet package using Visual Studio (.NET Standard, Windows only)
If you are using Visual Studio for Mac, refer to this information on creating a NuGet package, or use the dotnet CLI tools.
Prerequisites
If it’s not already installed, install the dotnet CLI.
Register for a free account on nuget.org if you don’t have one already. Creating a new account sends a confirmation email. You must confirm the account before you can upload a package.
Create a class library project
Right-click on the resulting project file and select Build to make sure the project was created properly. The DLL is found within the Debug folder (or Release if you build that configuration instead).
Within a real NuGet package, of course, you implement many useful features with which others can build applications. For this walkthrough, however, you won’t write any additional code because a class library from the template is sufficient to create a package. Still, if you’d like some functional code for the package, use the following:
Configure package properties
Right-click the project in Solution Explorer, and choose Properties menu command, then select the Package tab.
For packages built for public consumption, pay special attention to the Tags property, as tags help others find your package and understand what it does.
You must give the package an identifier that’s unique across nuget.org or whatever host you’re using. For this walkthrough we recommend including «Sample» or «Test» in the name as the later publishing step does make the package publicly visible (though it’s unlikely anyone will actually use it).
If you attempt to publish a package with a name that already exists, you see an error.
(Optional) To see the properties directly in the project file, right-click the project in Solution Explorer and select Edit AppLogger.csproj.
This option is only available starting in Visual Studio 2017 for projects that use the SDK-style attribute. Otherwise, right-click the project and choose Unload Project. Then right-click the unloaded project and choose Edit AppLogger.csproj.
Run the pack command
Set the configuration to Release.
Right click the project in Solution Explorer and select the Pack command:
(Optional) Generate package on build
You can configure Visual Studio to automatically generate the NuGet package when you build the project.
In Solution Explorer, right-click the project and choose Properties.
In the Package tab, select Generate NuGet package on build.
When you automatically generate the package, the time to pack increases the build time for your project.
(Optional) pack with MSBuild
As an alternate to using the Pack menu command, NuGet 4.x+ and MSBuild 15.1+ supports a pack target when the project contains the necessary package data. Open a command prompt, navigate to your project folder and run the following command. (You typically want to start the «Developer Command Prompt for Visual Studio» from the Start menu, as it will be configured with all the necessary paths for MSBuild.)
Publish the package
Virus scanning: All packages uploaded to nuget.org are scanned for viruses and rejected if any viruses are found. All packages listed on nuget.org are also scanned periodically.
Packages published to nuget.org are also publicly visible to other developers unless you unlist them. To host packages privately, see Hosting packages.
Acquire your API key
Sign into your nuget.org account or create an account if you don’t have one already.
For more information on creating your account, see Individual accounts.
Select your user name (on the upper right), then select API Keys.
Select Create, provide a name for your key, select Select Scopes > Push. Enter * for Glob pattern, then select Create. (See below for more about scopes.)
Once the key is created, select Copy to retrieve the access key you need in the CLI:
Always keep your API key a secret! Treat your API key as a password that allows anyone to manage packages on your behalf. You should delete or regenerate your API key if it is accidentally revealed.
Save your key in a secure location because you cannot copy the key again later on. If you return to the API key page, you need to regenerate the key to copy it. You can also remove the API key if you no longer want to push packages.
Scoping allows you to create separate API keys for different purposes. Each key has its expiration timeframe and can be scoped to specific packages (or glob patterns). Each key is also scoped to specific operations: push of new packages and updates, push of updates only, or delisting. Through scoping, you can create API keys for different people who manage packages for your organization such that they have only the permissions they need. For more information, see scoped API keys.
Publish with the dotnet CLI or nuget.exe CLI
Select the tab for your CLI tool, either .NET Core CLI (dotnet CLI) or NuGet (nuget.exe CLI).
Before you can publish the package, you must first open a command line.
Run the following command, specifying your package name (unique package ID) and replacing the key value with your API key:
dotnet displays the results of the publishing process:
Run the following command, specifying your package name (unique package ID) and replacing the key value with your API key:
nuget.exe displays the results of the publishing process:
Publish errors
Errors from the push command typically indicate the problem. For example, you may have forgotten to update the version number in your project and are therefore trying to publish a package that already exists.
You also see errors when trying to publish a package using an identifier that already exists on the host. The name «AppLogger», for example, already exists. In such a case, the push command gives the following error:
Manage the published package
From your profile on nuget.org, select Manage Packages to see the one you just published. You also receive a confirmation email. Note that it might take a while for your package to be indexed and appear in search results where others can find it. During that time your package page shows the message below:
And that’s it! You’ve just published your first NuGet package to nuget.org that other developers can use in their own projects.
If in this walkthrough you created a package that isn’t actually useful (such as a package created with an empty class library), you should unlist the package to hide it from search results:
On nuget.org, select your user name (upper right of the page), then select Manage Packages.
Locate the package you want to unlist under Published and select the trash can icon on the right:
On the subsequent page, clear the box labeled List (package-name) in search results and select Save:
Adding a readme and other files
To directly specify files to include in the package, edit the project file and use the content property:
This will include a file named readme.txt in the package root. Visual Studio displays the contents of that file as plain text immediately after installing the package directly. (Readme files are not displayed for packages installed as dependencies). For example, here’s how the readme for the HtmlAgilityPack package appears:
Merely adding the readme.txt at the project root will not result in it being included in the resulting package.
Related video
Find more NuGet videos on Channel 9 and YouTube.
Create a NuGet package using the dotnet CLI
Set properties
The following properties are required to create a package.
Give the package an identifier that’s unique across nuget.org or whatever package source you’re using.
The following example shows a simple, complete project file with these properties included. (You can create a new default project using the dotnet new classlib command.)
For packages built for public consumption, pay special attention to the PackageTags property, as tags help others find your package and understand what it does.
For details on declaring dependencies and specifying version numbers, see Package references in project files and Package versioning. It is also possible to surface assets from dependencies directly in the package by using the and attributes. For more information, see Controlling dependency assets.
Add an optional description field
Choose a unique package identifier and set the version number
The package identifier and the version number are the two most important values in the project because they uniquely identify the exact code that’s contained in the package.
Best practices for the package identifier:
Best practices for the package version:
For information on dependency resolution, see Dependency resolution with PackageReference. For older information that may also be helpful to better understand versioning, see this series of blog posts.
Run the pack command
Automatically generate package on build
When you run dotnet pack on a solution, this packs all the projects in the solution that are packable ( property is set to true ).
When you automatically generate the package, the time to pack increases the build time for your project.
Test package installation
Before publishing a package, you typically want to test the process of installing a package into a project. The tests make sure that the necessary files all end up in their correct places in the project.
You can test installations manually in Visual Studio or on the command line using the normal package installation steps.
Packages are immutable. If you correct a problem, change the contents of the package and pack again, when you retest you will still be using the old version of the package until you clear your global packages folder. This is especially relevant when testing packages that don’t use a unique prerelease label on every build.
Next Steps
You might also want to extend the capabilities of your package or otherwise support other scenarios as described in the following topics:
Finally, there are additional package types to be aware of:
Краткое руководство. Создание и публикация пакета NuGet с помощью Visual Studio (.NET Standard, только для Windows)
Если вы используете Visual Studio для Mac, ознакомьтесь с этими сведениями о создании пакета NuGet или примените средства CLI dotnet.
Предварительные требования
Зарегистрируйтесь для получения бесплатной учетной записи на nuget.org, если вы не сделали этого ранее. При создании учетной записи вам направляется сообщение электронной почты с подтверждением. Перед отправкой пакета вам нужно подтвердить учетную запись.
Создание проекта библиотеки классов
Щелкните правой кнопкой мыши полученный файл проекта и выберите пункт Сборка, чтобы убедиться, что проект создан правильно. Библиотека DLL находится в папке Debug (или папке Release, если вы используете конфигурацию выпуска для сборки).
В реальном пакете NuGet вы можете реализовать множество полезных возможностей, с помощью которых другие пользователи могут создавать приложения. Однако в этом пошаговом руководстве вы не будете писать дополнительный код, так как библиотеки классов из шаблона достаточно для создания пакета. Тем не менее, вы можете использовать функциональный код для пакета:
Настройка свойств пакета
Щелкните правой кнопкой мыши проект в обозреватель решений и выберите команду меню Свойства, а затем выберите вкладку Пакет.
Если пакет будет общедоступным, обратите особое внимание на свойство Теги, так как они помогают найти ваш пакет и понять его назначение.
Необходимо присвоить пакету идентификатор, который будет уникальным на сайте nuget.org или другом используемом узле. При работе с этим руководством мы рекомендуем добавить к имени слово «Sample» или «Test», так как позже, после публикации, пакет станет общедоступным (хотя маловероятно, что кто-то будет его использовать).
При попытке опубликовать пакет с именем, которое уже занято, появится сообщение об ошибке.
Необязательно. Чтобы просматривать свойства непосредственно в файле проекта, щелкните правой кнопкой мыши проект в обозревателе решений и выберите Edit AppLogger.csproj (Изменить AppLogger.csproj).
Этот параметр доступен для проектов, использующих атрибут стиля пакета SDK, только в версиях начиная с Visual Studio 2017. Если у вас другой сценарий, щелкните проект правой кнопкой мыши и выберите пункт Выгрузить проект. Затем щелкните правой кнопкой мыши выгруженный проект и выберите команду изменения AppLogger.csproj.
Выполнение команды pack
Выберите конфигурацию Выпуск.
Щелкните проект правой кнопкой мыши в окне обозревателя решений и выберите команду Паковать:
(Необязательно) Создание пакета при сборке
Вы можете настроить в Visual Studio автоматическое создание пакета NuGet при сборке проекта.
В обозревателе решений щелкните правой кнопкой мыши проект и выберите пункт Свойства.
На вкладке Пакет выберите Создать пакет NuGet при сборке.
При автоматическом создании пакета время на упаковку увеличивает время сборки проекта.
(Необязательно) Упаковка с помощью MSBuild
Дополнительные сведения см. в разделе Создание пакета с помощью MSBuild.
Публикация пакета
Проверка на вирусы: перед публикацией все пакеты, загружаемые на веб-сайт nuget.org, проверяются на вирусы, и в случае обнаружения вирусов отклоняются. Кроме того, периодическую проверку проходят все пакеты, представленные на веб-сайте nuget.org.
Пакеты, опубликованные на сайте nuget.org, доступны и для других разработчиков (пока вы не исключите их из списка). Чтобы разместить пакеты частным образом, см. раздел Размещение пакетов.
Получение ключа API
Войдите в учетную запись nuget.org или создайте учетную запись (если ее еще нет).
Выберите свое имя пользователя (в правом верхнем углу), а затем щелкните Ключи API.
Щелкните команду Create (Создать), введите имя ключа, а затем выберите элементы Select Scopes (Выбрать области) > Push (Отправить). Введите * в поле Glob pattern (Стандартная маска), а затем выберите Create (Создать). (Дополнительные сведения об областях см. ниже.)
После создания ключа выберите Копировать для получения ключа доступа, который требуется в интерфейсе командной строки:
Всегда держите свой ключ API в секрете! Рассматривайте свой ключ API как пароль, позволяющий любому пользователю управлять пакетами от вашего имени. Вам следует удалить или повторно создать свой ключ API, если он был случайно раскрыт.
Сохраните ключ в безопасном расположении, так как у вас больше не будет возможности скопировать ключ. Если вы вернетесь на страницу ключа API, вам понадобится повторно создать ключ, чтобы скопировать его. Кроме того, вы можете удалить ключ API, если больше не хотите отправлять пакеты.
Определение области позволяет создавать отдельные ключи API для разных целей. Ключи имеют срок действия. Кроме того, их можно привязать к определенным пакетам (или стандартным маскам). Каждый ключ также привязан к конкретным операциям: отправка новых пакетов и обновлений, отправка только обновлений или удаление из списка. Используя определение области, вы можете создавать ключи API разным пользователям, которые управляют пакетами организации. Это позволит предоставлять им только нужные разрешения. См. подробнее о ключах API в определении области.
Публикация с помощью CLI dotnet или CLI nuget.exe
Выберите вкладку для своего инструмента CLI: .NET Core CLI (для CLI dotnet) или NuGet (для CLI nuget.exe).
Перед публикацией пакета сначала нужно открыть командную строку.
Выполните следующую команду, указав имя пакета (уникальный идентификатор пакета) и заменив значение ключа ключом API:
dotnet отображает результаты публикации:
Дополнительные сведения см. в статье о команде dotnet nuget push.
Выполните следующую команду, указав имя пакета (уникальный идентификатор пакета) и заменив значение ключа ключом API:
nuget.exe отображает результаты публикации:
Ознакомьтесь со сведениями о команде nuget push.
Ошибки публикации
Ошибки в результатах выполнения команды push обычно указывают на неполадку. Например, вы забыли обновить номер версии проекта и пытаетесь опубликовать пакет, который уже существует.
Ошибки также возникают при попытке опубликовать пакет с использованием идентификатора, который уже имеется на узле. Например, имя AppLogger уже существует. В этом случае команда push выдает следующую ошибку:
Управление опубликованным пакетом
В своем профиле на сайте nuget.org выберите Manage Packages (Управление пакетами), чтобы просмотреть опубликованный вами пакет. Вы также получите подтверждение по электронной почте. Обратите внимание, что пакет индексируется и будет появляться в результатах поиска для других пользователей спустя определенное время. В этот период на странице вашего пакета отображается следующее сообщение:
Вот и все! Вы только что опубликовали на сайте nuget.org свой первый пакет NuGet, который другие разработчики могут использовать в своих собственных проектах.
Если при работе с этим пошаговым руководством был создан пакет, который не представляет пользы (например, пакет, созданный с использованием пустой библиотеки классов), следует исключить его из списка, чтобы он не отображался в результатах поиска:
На сайте nuget.org выберите имя пользователя (в верхнем правом углу страницы), а затем Manage Packages (Управление пакетами).
Найдите пакет, который требуется исключить из списка, в разделе Published (Опубликованное) и щелкните значок корзины справа:
На следующей странице снимите флажок List (package-name) in search results (Вывести (имя пакета) в результатах поиска) и щелкните Save (Сохранить).
Добавление файла сведений и других файлов
Чтобы напрямую указать файлы, включаемые в пакет, измените файл проекта и используйте свойство content :
Обычное добавление файла readme.txt в корень проекта не приведет к включению его в итоговый пакет.
Связанные видео
Другие видео о NuGet см. на Channel 9 и YouTube.
Quickstart: Create and publish a package (dotnet CLI)
Prerequisites
Register for a free account on nuget.org if you don’t have one already. Creating a new account sends a confirmation email. You must confirm the account before you can upload a package.
Create a class library project
Open a command prompt and switch to the AppLogger folder.
This creates the new project.
Add package metadata to the project file
tag, changing the values as appropriate:
Give the package an identifier that’s unique across nuget.org or whatever host you’re using. For this walkthrough we recommend including «Sample» or «Test» in the name as the later publishing step does make the package publicly visible (though it’s unlikely anyone will actually use it).
Add any optional properties described on NuGet metadata properties.
For packages built for public consumption, pay special attention to the PackageTags property, as tags help others find your package and understand what it does.
Run the pack command
Automatically generate package on build
Publish the package
Virus scanning: All packages uploaded to nuget.org are scanned for viruses and rejected if any viruses are found. All packages listed on nuget.org are also scanned periodically.
Packages published to nuget.org are also publicly visible to other developers unless you unlist them. To host packages privately, see Hosting packages.
Acquire your API key
Sign into your nuget.org account or create an account if you don’t have one already.
For more information on creating your account, see Individual accounts.
Select your user name (on the upper right), then select API Keys.
Select Create, provide a name for your key, select Select Scopes > Push. Enter * for Glob pattern, then select Create. (See below for more about scopes.)
Once the key is created, select Copy to retrieve the access key you need in the CLI:
Always keep your API key a secret! Treat your API key as a password that allows anyone to manage packages on your behalf. You should delete or regenerate your API key if it is accidentally revealed.
Save your key in a secure location because you cannot copy the key again later on. If you return to the API key page, you need to regenerate the key to copy it. You can also remove the API key if you no longer want to push packages.
Scoping allows you to create separate API keys for different purposes. Each key has its expiration timeframe and can be scoped to specific packages (or glob patterns). Each key is also scoped to specific operations: push of new packages and updates, push of updates only, or delisting. Through scoping, you can create API keys for different people who manage packages for your organization such that they have only the permissions they need. For more information, see scoped API keys.
Publish with dotnet nuget push
Run the following command, specifying your package name (unique package ID) and replacing the key value with your API key:
dotnet displays the results of the publishing process:
Publish errors
Errors from the push command typically indicate the problem. For example, you may have forgotten to update the version number in your project and are therefore trying to publish a package that already exists.
You also see errors when trying to publish a package using an identifier that already exists on the host. The name «AppLogger», for example, already exists. In such a case, the push command gives the following error:
Manage the published package
From your profile on nuget.org, select Manage Packages to see the one you just published. You also receive a confirmation email. Note that it might take a while for your package to be indexed and appear in search results where others can find it. During that time your package page shows the message below:
And that’s it! You’ve just published your first NuGet package to nuget.org that other developers can use in their own projects.
If in this walkthrough you created a package that isn’t actually useful (such as a package created with an empty class library), you should unlist the package to hide it from search results:
On nuget.org, select your user name (upper right of the page), then select Manage Packages.
Locate the package you want to unlist under Published and select the trash can icon on the right:
On the subsequent page, clear the box labeled List (package-name) in search results and select Save:
Related video
Find more NuGet videos on Channel 9 and YouTube.
Next steps
Congratulations on creating your first NuGet package!
To explore more that NuGet has to offer, select the links below.
Источники информации:
- http://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package-using-visual-studio
- http://docs.microsoft.com/en-us/nuget/create-packages/creating-a-package-dotnet-cli
- http://docs.microsoft.com/ru-ru/nuget/quickstart/create-and-publish-a-package-using-visual-studio
- http://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package-using-the-dotnet-cli