.nuspec 參考.nuspec reference

.nuspec 檔案是包含套件中繼資料的 XML 資訊清單。A .nuspec file is an XML manifest that contains package metadata. 此資訊清單用來建置套件和向取用者提供資訊。This manifest is used both to build the package and to provide information to consumers. 資訊清單一律包含在套件中。The manifest is always included in a package.

本主題內容:In this topic:

專案類型相容性Project type compatibility

一般格式和結構描述General form and schema

目前的 nuspec.xsd 結構描述檔案位於 NuGet GitHub 存放庫The current nuspec.xsd schema file can be found in the NuGet GitHub repository.

在此結構描述內,.nuspec 檔案有下列一般格式:Within this schema, a .nuspec file has the following general form:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <!-- Required elements-->
        <id></id>
        <version></version>
        <description></description>
        <authors></authors>

        <!-- Optional elements -->
        <!-- ... -->
    </metadata>
    <!-- Optional 'files' node -->
</package>

為能清晰呈現結構描述,請在 Visual Studio 中以設計模式開啟結構描述檔案,按一下 [XML 結構描述總管] 連結。For a clear visual representation of the schema, open the schema file in Visual Studio in Design mode and click on the XML Schema Explorer link. 或者,將檔案開啟為程式碼,在編輯器中按一下滑鼠右鍵,選取 [Show XML Schema Explorer] (顯示 XML 結構描述總管)。Alternately, open the file as code, right-click in the editor, and select Show XML Schema Explorer. 任一方式都可取得類似以下的檢視 (大部分展開時):Either way you get a view like the one below (when mostly expanded):

開啟了 nuspec.xsd 的 Visual Studio 結構描述總管

必要的中繼資料項目Required metadata elements

雖然下列項目是套件的最低需求,但您應該考慮新增選擇性中繼資料項目以改善開發人員使用套件的整體體驗。Although the following elements are the minimum requirements for a package, you should consider adding the optional metadata elements to improve the overall experience developers have with your package.

這些項目必須出現在 <metadata> 項目中。These elements must appear within a <metadata> element.

idid

不區分大小寫的套件識別碼,在整個 nuget.org 或套件所在的任何組件庫中都必須是唯一的。The case-insensitive package identifier, which must be unique across nuget.org or whatever gallery the package resides in. 識別碼可能不包含對 URL 而言無效的空格或字元,而且通常會遵循 .NET 命名空間規則。IDs may not contain spaces or characters that are not valid for a URL, and generally follow .NET namespace rules. 如需指導方針,請參閱選擇唯一的套件識別碼See Choosing a unique package identifier for guidance.

versionversion

套件版本,遵循 major.minor.patch 模式。The version of the package, following the major.minor.patch pattern. 版本號碼可以包含預先發行版本的後置詞,如套件版本控制中所述。Version numbers may include a pre-release suffix as described in Package versioning.

描述description

UI 顯示的封裝描述。A description of the package for UI display.

authorsauthors

以逗號分隔的套件作者清單,與 nuget.org 上的設定檔名稱相符。這些會顯示在 nuget.org 上的 NuGet 元件庫中,並用於相同作者的交互參照封裝。A comma-separated list of packages authors, matching the profile names on nuget.org. These are displayed in the NuGet Gallery on nuget.org and are used to cross-reference packages by the same authors.

選擇性中繼資料項目Optional metadata elements

ownersowners

在 nuget.org 上使用設定檔名稱的套件建立者清單(以逗號分隔)。這通常與 authors 中的清單相同,並會在將封裝上傳至 nuget.org 時予以忽略。請參閱在 nuget.org 上管理套件擁有者。A comma-separated list of the package creators using profile names on nuget.org. This is often the same list as in authors, and is ignored when uploading the package to nuget.org. See Managing package owners on nuget.org.

projectUrlprojectUrl

套件首頁的 URL,通常會顯示在 UI 顯示及 nuget.org 中。A URL for the package's home page, often shown in UI displays as well as nuget.org.

licenseUrllicenseUrl

重要

licenseUrl 已被取代。licenseUrl is deprecated. 請改用授權。Use license instead.

套件授權的 URL,通常會顯示在像是 nuget.org 的 Ui 中。A URL for the package's license, often shown in UIs like nuget.org.

執照license

封裝內授權檔案的 SPDX 授權運算式或路徑,通常會顯示在類似 nuget.org 的 Ui 中。如果您要以一般授權(例如 MIT 或 BSD-2-子句)授權封裝,請使用相關聯的SPDX 授權識別碼An SPDX license expression or path to a license file within the package, often shown in UIs like nuget.org. If you're licensing the package under a common license, like MIT or BSD-2-Clause, use the associated SPDX license identifier. 例如:For example:

<license type="expression">MIT</license>

注意

NuGet.org 只接受開放原始碼計畫或免費軟體基礎核准的授權運算式。NuGet.org only accepts license expressions that are approved by the Open Source Initiative or the Free Software Foundation.

如果您的套件是以多個一般授權授權,您可以使用SPDX 運算式語法2.0 版來指定複合授權。If your package is licensed under multiple common licenses, you can specify a composite license using the SPDX expression syntax version 2.0. 例如:For example:

<license type="expression">BSD-2-Clause OR MIT</license>

如果您使用授權運算式不支援的自訂授權,您可以使用授權文字來封裝 .txt.md 檔案。If you use a custom license that isn't supported by license expressions, you can package a .txt or .md file with the license's text. 例如:For example:

<package>
  <metadata>
    ...
    <license type="file">LICENSE.txt</license>
    ...
  </metadata>
  <files>
    ...
    <file src="licenses\LICENSE.txt" target="" />
    ...
  </files>
</package>

如需對等的 MSBuild,請參閱封裝授權運算式或授權檔案For the MSBuild equivalent, take a look at Packing a license expression or a license file.

NuGet 授權運算式的確切語法在下面的ABNF中有說明。The exact syntax of NuGet's license expressions is described below in ABNF.

license-id            = <short form license identifier from https://spdx.org/spdx-specification-21-web-version#h.luq9dgcle9mo>

license-exception-id  = <short form license exception identifier from https://spdx.org/spdx-specification-21-web-version#h.ruv3yl8g6czd>

simple-expression = license-id / license-id”+”

compound-expression =  1*1(simple-expression /
                simple-expression "WITH" license-exception-id /
                compound-expression "AND" compound-expression /
                compound-expression "OR" compound-expression ) /                
                "(" compound-expression ")" )

license-expression =  1*1(simple-expression / compound-expression / UNLICENSED)

iconUrliconUrl

重要

iconUrl 已被取代。iconUrl is deprecated. 請改用圖示。Use icon instead.

具有透明背景之 64x64 映像的 URL,該映像會用作套件在 UI 顯示中的圖示。A URL for a 64x64 image with transparency background to use as the icon for the package in UI display. 確定這個項目包含「直接映像 URL」,不是包含影像的網頁 URL。Be sure this element contains the direct image URL and not the URL of a web page containing the image. 例如,若要使用 GitHub 中的映射,請使用原始檔案 URL,例如https://github.com/<username>/<repository>/raw/<branch>/<logo.png>For example, to use an image from GitHub, use the raw file URL like https://github.com/<username>/<repository>/raw/<branch>/<logo.png>.

圖示icon

它是封裝內影像檔案的路徑,通常會顯示在像是 nuget.org 的 Ui 中,做為封裝圖示。It is a path to an image file within the package, often shown in UIs like nuget.org as the package icon. 影像檔案大小限制為 1 MB。Image file size is limited to 1 MB. 支援的檔案格式包括 JPEG 和 PNG。Supported file formats include JPEG and PNG. 我們建議使用64x64 的影像 resoulution。We recommend an image resoulution of 64x64.

例如,當您使用 nuget.exe 建立套件時,會將下列內容新增至您的 nuspec:For example, you would add the following to your nuspec when creating a package using nuget.exe:

<package>
  <metadata>
    ...
    <icon>images\icon.png</icon>
    ...
  </metadata>
  <files>
    ...
    <file src="..\icon.png" target="images\" />
    ...
  </files>
</package>

封裝圖示 nuspec 範例。Package Icon nuspec sample.

如需對等的 MSBuild,請參閱封裝圖示影像檔For the MSBuild equivalent, take a look at Packing an icon image file.

提示

您可以指定 iconiconUrl,以維持與不支援 icon的來源的回溯相容性。You can specify both icon and iconUrl to maintain backward compatibility with sources that do not support icon. Visual Studio 將支援未來版本中來自以資料夾為基礎的來源之套件的 iconVisual Studio will support icon for packages coming from a folder-based source in a future release.

requireLicenseAcceptancerequireLicenseAcceptance

布林值,指定在安裝套件時,用戶端是否必須提示取用者接受套件授權。A Boolean value specifying whether the client must prompt the consumer to accept the package license before installing the package.

developmentDependencydevelopmentDependency

(2.8+) 布林值,指定套件是否標示為僅限開發相依性,這可防止套件包含為其他套件的相依性。(2.8+) A Boolean value specifying whether the package is be marked as a development-only-dependency, which prevents the package from being included as a dependency in other packages. 使用 PackageReference (NuGet 4.8 +)時,此旗標也表示它會從編譯中排除編譯時間資產。With PackageReference (NuGet 4.8+), this flag also means that it will exclude compile-time assets from compilation. 請參閱DevelopmentDependency support For PackageReferenceSee DevelopmentDependency support for PackageReference

摘要summary

重要

summary 已被取代。summary is being deprecated. 請改用 descriptionUse description instead.

UI 顯示中的套件簡短描述。A short description of the package for UI display. 如果省略,即使用截斷版本的 descriptionIf omitted, a truncated version of description is used.

releaseNotesreleaseNotes

(1.5+) 此版本套件中的變更描述,通常用於 Visual Studio Package Manager 的 [更新] 索引標籤等 UI 中,以取代套件描述。(1.5+) A description of the changes made in this release of the package, often used in UI like the Updates tab of the Visual Studio Package Manager in place of the package description.

(1.5+) 套件的著作權詳細資料。(1.5+) Copyright details for the package.

語言language

套件的地區設定識別碼。The locale ID for the package. 請參閱建立當地語系化的套件See Creating localized packages.

標記tags

以逗號分隔的標記與關鍵字清單,描述套件並透過搜尋和篩選協助探索套件。A space-delimited list of tags and keywords that describe the package and aid discoverability of packages through search and filtering.

一次性serviceable

(3.3+) 僅供內部 NuGet 使用。(3.3+) For internal NuGet use only.

儲存機制repository

存放庫中繼資料,由四個選擇性屬性組成: typeurl (4.0 +) ,以及 branchcommit (4.6 +)Repository metadata, consisting of four optional attributes: type and url (4.0+), and branch and commit (4.6+). 這些屬性可讓您將 .nupkg 對應至建立它的存放庫,而且可能會如個別分支名稱和/或認可建立封裝的 SHA-1 雜湊來取得詳細資訊。These attributes allow you to map the .nupkg to the repository that built it, with the potential to get as detailed as the individual branch name and / or commit SHA-1 hash that built the package. 這應該是公開可用的 url,可直接由版本控制軟體叫用。This should be a publicly available url that can be invoked directly by a version control software. 它不應該是 html 網頁,因為這適用于電腦。It should not be an html page as this is meant for the computer. 在 [連結至專案] 頁面上,改為使用 [projectUrl] 欄位。For linking to project page, use the projectUrl field, instead.

例如:For example:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2016/06/nuspec.xsd">
    <metadata>
        ...
        <repository type="git" url="https://github.com/NuGet/NuGet.Client.git" branch="dev" commit="e1c65e4524cd70ee6e22abe33e6cb6ec73938cb3" />
        ...
    </metadata>
</package>

標題title

可在某些 UI 中使用之套件的人易記標題。A human-friendly title of the package which may be used in some UI displays. (nuget.org 和 Visual Studio 中的套件管理員不會顯示標題)(nuget.org and the Package Manager in Visual Studio do not show title)

集合項目Collection elements

Packagetypes>packageTypes

(3.5+) 零或多個 <packageType> 元素的集合,如果不是傳統相依性套件,則會指定套件類型。(3.5+) A collection of zero or more <packageType> elements specifying the type of the package if other than a traditional dependency package. 每個 packageType 都有「名稱」和「版本」屬性。Each packageType has attributes of name and version. 請參閱設定套件類型See Setting a package type.

相依性dependencies

零或多個 <dependency> 項目的集合,指定套件的相依性。A collection of zero or more <dependency> elements specifying the dependencies for the package. 每個相依性都有「識別碼」、「版本」、「包含」(3.x+) 和「排除」(3.x+) 屬性。Each dependency has attributes of id, version, include (3.x+), and exclude (3.x+). 請參閱下文的相依性See Dependencies below.

frameworkAssembliesframeworkAssemblies

(1.2+) 零或多個 <frameworkAssembly> 項目的集合,識別此套件需要的 .NET Framework 組件參考,它們可確保參考會新增至取用套件的專案。(1.2+) A collection of zero or more <frameworkAssembly> elements identifying .NET Framework assembly references that this package requires, which ensures that references are added to projects consuming the package. 每個 frameworkAssembly 都有 assemblyNametargetFramework 屬性。Each frameworkAssembly has assemblyName and targetFramework attributes. 請參閱下文的指定 Framework 組件參考 GACSee Specifying framework assembly references GAC below.

參考references

(1.5+) 在套件的 lib 資料夾中命名組件的零或多個 <reference> 項目集合,這些項目可新增為專案參考。(1.5+) A collection of zero or more <reference> elements naming assemblies in the package's lib folder that are added as project references. 每個參考都有 file 屬性。Each reference has a file attribute. <references> 也可以包含具有 targetFramework 屬性的 <group> 項目,然後即可包含 <reference> 項目。<references> can also contain a <group> element with a targetFramework attribute, that then contains <reference> elements. 如果省略,就會包含 lib 中的所有參考。If omitted, all references in lib are included. 請參閱下文中的指定明確的組件參考See Specifying explicit assembly references below.

contentFilescontentFiles

(3.3+) <files> 項目的集合,可識別要包含在取用專案中的內容檔案。(3.3+) A collection of <files> elements that identify content files to include in the consuming project. 這些檔案是由一組描述如何在專案系統內使用它們的屬性所指定。These files are specified with a set of attributes that describe how they should be used within the project system. 請參閱下文中的指定要包含在套件中的檔案See Specifying files to include in the package below.

個檔案files

<package> 節點可能會包含 <files> 節點做為 <metadata>的同級,以及 <metadata>下的 <contentFiles> 子系,以指定要包含在封裝中的元件和內容檔案。The <package> node may contain a <files> node as a sibling to <metadata>, and a <contentFiles> child under <metadata>, to specify which assembly and content files to include in the package. 如需詳細資料,請參閱本主題下文中的包含組件檔包含內容檔See Including assembly files and Including content files later in this topic for details.

中繼資料屬性metadata attributes

minClientVersionminClientVersion

指定可安裝此套件的最低 NuGet 用戶端版本,此作業是由 nuget.exe 和 Visual Studio 套件管理員強制執行。Specifies the minimum version of the NuGet client that can install this package, enforced by nuget.exe and the Visual Studio Package Manager. 每當套件依存於 NuGet 用戶端新增的 .nuspec 檔案特定功能時,就會使用。This is used whenever the package depends on specific features of the .nuspec file that were added in a particular version of the NuGet client. 例如,套件使用的 developmentDependency 屬性應該為 minClientVersion 指定 "2.8"。For example, a package using the developmentDependency attribute should specify "2.8" for minClientVersion. 同樣地,使用 contentFiles 項目的套件 (請參閱下一節) 應將 minClientVersion 設定成 "3.3"。Similarly, a package using the contentFiles element (see the next section) should set minClientVersion to "3.3". 另請注意,因為 2.5 之前的 NuGet 用戶端無法辨識此旗標,所以它們「一律」拒絕安裝套件,無論 minClientVersion 包含什麼。Note also that because NuGet clients prior to 2.5 do not recognize this flag, they always refuse to install the package no matter what minClientVersion contains.

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/01/nuspec.xsd">
    <metadata minClientVersion="100.0.0.1">
        <id>dasdas</id>
        <version>2.0.0</version>
        <title />
        <authors>dsadas</authors>
        <owners />
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <description>My package description.</description>
    </metadata>
    <files>
        <file src="content\one.txt" target="content\one.txt" />
    </files>
</package>

取代權杖Replacement tokens

建立套件時,nuget pack 命令 會使用來自專案檔的值或來自 pack 命令的 -properties 參數值,取代 .nuspec 檔案之 <metadata> 節點的 $ 分隔權杖。When creating a package, the nuget pack command replaces $-delimited tokens in the .nuspec file's <metadata> node with values that come from either a project file or the pack command's -properties switch.

在命令列中,您可以使用 nuget pack -properties <name>=<value>;<name>=<value> 指定權杖值。On the command line, you specify token values with nuget pack -properties <name>=<value>;<name>=<value>. 例如,您可以在 .nuspec 中使用權杖,例如 $owners$$desc$,並在封裝階段提供值,如下所示:For example, you can use a token such as $owners$ and $desc$ in the .nuspec and provide the values at packing time as follows:

nuget pack MyProject.csproj -properties
    owners=janedoe,harikm,kimo,xiaop;desc="Awesome app logger utility"

若要使用專案中的值,請指定下表中描述的權杖 (AssemblyInfo 是指 Properties 中的檔案,例如 AssemblyInfo.csAssemblyInfo.vb)。To use values from a project, specify the tokens described in the table below (AssemblyInfo refers to the file in Properties such as AssemblyInfo.cs or AssemblyInfo.vb).

若要使用這些權杖,請執行 nuget pack 與專案檔,非僅 .nuspecTo use these tokens, run nuget pack with the project file rather than just the .nuspec. 例如,使用下列命令時,專案的 AssemblyNameAssemblyVersion 值會取代為 .nuspec 檔案中的 $id$$version$ 權杖:For example, when using the following command, the $id$ and $version$ tokens in a .nuspec file are replaced with the project's AssemblyName and AssemblyVersion values:

nuget pack MyProject.csproj

通常,當您擁有專案時,一開始會使用自動包含這些標準權杖一部分的 nuget spec MyProject.csproj 來建立 .nuspecTypically, when you have a project, you create the .nuspec initially using nuget spec MyProject.csproj which automatically includes some of these standard tokens. 不過,如果專案沒有所需之 .nuspec 項目的值,則 nuget pack 會失敗。However, if a project lacks values for required .nuspec elements, then nuget pack fails. 此外,如果變更專案值,請務必在建立套件前重建;使用 pack 命令的 build 參數很容易完成此作業。Furthermore, if you change project values, be sure to rebuild before creating the package; this can be done conveniently with the pack command's build switch.

$configuration$ 以外,專案中值的使用順序優先於任何指派給命令列上相同權杖的值。With the exception of $configuration$, values in the project are used in preference to any assigned to the same token on the command line.

語彙基元Token 值來源Value source Value
$id$$id$ 專案檔Project file 專案檔中的 AssemblyName (title)AssemblyName (title) from the project file
$version$$version$ AssemblyInfoAssemblyInfo 如有則為 AssemblyInformationalVersion,否則為 AssemblyVersionAssemblyInformationalVersion if present, otherwise AssemblyVersion
$author$$author$ AssemblyInfoAssemblyInfo AssemblyCompanyAssemblyCompany
$title $$title$ AssemblyInfoAssemblyInfo AssemblyTitleAssemblyTitle
$description$$description$ AssemblyInfoAssemblyInfo AssemblyDescriptionAssemblyDescription
$copyright$$copyright$ AssemblyInfoAssemblyInfo AssemblyCopyrightAssemblyCopyright
$configuration$$configuration$ 組件 DLLAssembly DLL 用以建置組件的組態,預設為偵錯。Configuration used to build the assembly, defaulting to Debug. 請注意,若要建立使用版本組態的套件,命令列上一律要使用 -properties Configuration=ReleaseNote that to create a package using a Release configuration, you always use -properties Configuration=Release on the command line.

當您包含組件檔內容檔時,也可使用權杖來解析路徑。Tokens can also be used to resolve paths when you include assembly files and content files. 權杖和 MSBuild 屬性有相同的名稱,所以您才能夠根據目前的組建組態選取要包含的檔案。The tokens have the same names as the MSBuild properties, making it possible to select files to be included depending on the current build configuration. 例如,如果在 .nuspec 檔案中使用下列權杖:For example, if you use the following tokens in the .nuspec file:

<files>
    <file src="bin\$configuration$\$id$.pdb" target="lib\net40" />
</files>

而您建置的組件,其 AssemblyName 是在 MSBuild 中有 Release 組態的 LoggingLibrary,在套件的 .nuspec 檔案中產生的程式碼如下:And you build an assembly whose AssemblyName is LoggingLibrary with the Release configuration in MSBuild, the resulting lines in the .nuspec file in the package is as follows:

<files>
    <file src="bin\Release\LoggingLibrary.pdb" target="lib\net40" />
</files>

相依性元素Dependencies element

<metadata> 內的 <dependencies> 項目包含任意數目的 <dependency> 項目,可識別最上層套件依存的其他套件。The <dependencies> element within <metadata> contains any number of <dependency> elements that identify other packages upon which the top-level package depends. 每個 <dependency> 的屬性如下:The attributes for each <dependency> are as follows:

屬性Attribute 描述Description
id (必要) 相依性的套件識別碼,例如 "EntityFramework" 與 "NUnit",是在套件頁面上顯示的套件 nuget.org 名稱。(Required) The package ID of the dependency, such as "EntityFramework" and "NUnit", which is the name of the package nuget.org shows on a package page.
version (必要) 可接受為相依性的版本範圍。(Required) The range of versions acceptable as a dependency. 如需確切的語法,請參閱套件版本控制See Package versioning for exact syntax. 不支援萬用字元(浮動)版本。Wildcard (floating) versions are not supported.
includeinclude 包含/排除標記的逗號分隔清單 (如下所示),指出最終套件要包含的相依性。A comma-delimited list of include/exclude tags (see below) indicating of the dependency to include in the final package. 預設值是 allThe default value is all.
excludeexclude 包含/排除標記的逗號分隔清單 (如下所示),指出最終套件要排除的相依性。A comma-delimited list of include/exclude tags (see below) indicating of the dependency to exclude in the final package. 預設值是可覆寫的 build,analyzersThe default value is build,analyzers which can be over-written. 但是 content/ ContentFiles 也會在最終封裝中以隱含方式排除,而無法覆寫。But content/ ContentFiles are also implicitly excluded in the final package which can't be over-written. exclude 指定的標記優先於以 include 指定的標記。Tags specified with exclude take precedence over those specified with include. 例如,include="runtime, compile" exclude="compile"include="runtime" 相同。For example, include="runtime, compile" exclude="compile" is the same as include="runtime".
包含/排除標記Include/Exclude tag 目標的受影響資料夾Affected folders of the target
contentFilescontentFiles 內容Content
runtimeruntime 執行階段、資源和 FrameworkAssembliesRuntime, Resources, and FrameworkAssemblies
compilecompile liblib
buildbuild 組建 (MSBuild props 和目標)build (MSBuild props and targets)
nativenative nativenative
nonenone 無資料夾No folders
allall 全部資料夾All folders

例如,下列幾行程式碼指出 PackageA1.1.0 版或更高版本與 PackageB 1.x 版的相依性。For example, the following lines indicate dependencies on PackageA version 1.1.0 or higher, and PackageB version 1.x.

<dependencies>
    <dependency id="PackageA" version="1.1.0" />
    <dependency id="PackageB" version="[1,2)" />
</dependencies>

下列幾行程式碼指出相同套件的相依性,但指定要包含 PackageAcontentFilesbuild 資料夾,以及 PackageBnativecompile 資料夾以外的所有一切The following lines indicate dependencies on the same packages, but specify to include the contentFiles and build folders of PackageA and everything but the native and compile folders of PackageB"

<dependencies>
    <dependency id="PackageA" version="1.1.0" include="contentFiles, build" />
    <dependency id="PackageB" version="[1,2)" exclude="native, compile" />
</dependencies>

重要

使用 nuget spec 從專案建立 .nuspec 時,存在於該專案中的相依性不會自動包含在產生的 .nuspec 檔中。When creating a .nuspec from a project using nuget spec, dependencies that exist in that project are not automatically included in the resulting .nuspec file. 相反地,請使用 nuget pack myproject.csproj,然後從產生的nupkg檔案內取得nuspec檔案。Instead, use nuget pack myproject.csproj, and get the .nuspec file from within the generated .nupkg file. Nuspec包含相依性。This .nuspec contains the dependencies.

相依性群組Dependency groups

2.0+ 版Version 2.0+

當作單一一般清單的替代方案,您可以使用 <dependencies> 內的 <group> 項目,根據目標專案的 Framework 設定檔指定相依性。As an alternative to a single flat list, dependencies can be specified according to the framework profile of the target project using <group> elements within <dependencies>.

每個群組都有名為 targetFramework 的屬性,且包含零或多個 <dependency> 項目。Each group has an attribute named targetFramework and contains zero or more <dependency> elements. 當目標 Framework 與專案的 Framework 設定檔相容時,會同時安裝這些相依性。Those dependencies are installed together when the target framework is compatible with the project's framework profile.

沒有 targetFramework 屬性的 <group> 項目用為預設值或後援相依性清單。The <group> element without a targetFramework attribute is used as the default or fallback list of dependencies. 如需確切的 Framework 識別碼,請參閱目標 FrameworkSee Target frameworks for the exact framework identifiers.

重要

群組格式無法和一般清單混合使用。The group format cannot be intermixed with a flat list.

下列範例示範 <group> 項目的不同變化:The following example shows different variations of the <group> element:

<dependencies>
    <group>
        <dependency id="RouteMagic" version="1.1.0" />
    </group>

    <group targetFramework="net40">
        <dependency id="jQuery" version="1.6.2" />
        <dependency id="WebActivator" version="1.4.4" />
    </group>

    <group targetFramework="sl30">
    </group>
</dependencies>

明確的組件參考Explicit assembly references

使用 packages.config 的專案會使用 <references> 元素,明確指定使用封裝時,目標專案應參考的元件。The <references> element is used by projects using packages.config to explicitly specify the assemblies that the target project should reference when using the package. 明確參考通常只用於設計階段的組件。Explicit references are typically used for design-time only assemblies. 如需詳細資訊,請參閱選取專案所參考的元件中的頁面以取得詳細資訊。For more information, see the page on selecting assemblies referenced by projects for more information.

例如,以下 <references> 項目會指示 NuGet 只將參考新增至 xunit.dllxunit.extensions.dll,即使套件中有其他組件:For example, the following <references> element instructs NuGet to add references to only xunit.dll and xunit.extensions.dll even if there are additional assemblies in the package:

<references>
    <reference file="xunit.dll" />
    <reference file="xunit.extensions.dll" />
</references>

參考群組Reference groups

當作單一一般清單的替代方案,您可以使用 <references> 內的 <group> 項目,根據目標專案的 Framework 設定檔指定參考。As an alternative to a single flat list, references can be specified according to the framework profile of the target project using <group> elements within <references>.

每個群組都有名為 targetFramework 的屬性,且包含零或多個 <reference> 項目。Each group has an attribute named targetFramework and contains zero or more <reference> elements. 當目標 Framework 與專案的 Framework 設定檔相容時,這些參考會新增至專案。Those references are added to a project when the target framework is compatible with the project's framework profile.

沒有 targetFramework 屬性的 <group> 項目用為預設值或後援參考清單。The <group> element without a targetFramework attribute is used as the default or fallback list of references. 如需確切的 Framework 識別碼,請參閱目標 FrameworkSee Target frameworks for the exact framework identifiers.

重要

群組格式無法和一般清單混合使用。The group format cannot be intermixed with a flat list.

下列範例示範 <group> 項目的不同變化:The following example shows different variations of the <group> element:

<references>
    <group>
        <reference file="a.dll" />
    </group>

    <group targetFramework="net45">
        <reference file="b45.dll" />
    </group>

    <group targetFramework="netcore45">
        <reference file="bcore45.dll" />
    </group>
</references>

Framework 組件參考Framework assembly references

Framework 組件屬於 .NET Framework,應該已經在任何指定電腦的全域組件快取 (GAC) 中。Framework assemblies are those that are part of the .NET framework and should already be in the global assembly cache (GAC) for any given machine. 找出 <frameworkAssemblies> 項目內的這些組件,套件可以確保所需的參考已新增至事件的專案,該專案尚未有這類參考。By identifying those assemblies within the <frameworkAssemblies> element, a package can ensure that required references are added to a project in the event that the project doesn't have such references already. 當然,這類組件不直接包含在套件中。Such assemblies, of course, are not included in a package directly.

<frameworkAssemblies> 項目包含零或多個 <frameworkAssembly> 項目,它們每一個都會指定下列屬性:The <frameworkAssemblies> element contains zero or more <frameworkAssembly> elements, each of which specifies the following attributes:

屬性Attribute 描述Description
assemblyNameassemblyName (必要) 完整組件名稱。(Required) The fully qualified assembly name.
targetFrameworktargetFramework (選擇性) 指定要套用這個參考的目標 Framework。(Optional) Specifies the target framework to which this reference applies. 如果省略,則表示參考適用於所有 Framework。If omitted, indicates that the reference applies to all frameworks. 如需確切的 Framework 識別碼,請參閱目標 FrameworkSee Target frameworks for the exact framework identifiers.

下列範例會顯示所有目標 Framework 的 System.Net 參考,以及僅供 .NET Framework 4.0 使用的 System.ServiceModel 參考:The following example shows a reference to System.Net for all target frameworks, and a reference to System.ServiceModel for .NET Framework 4.0 only:

<frameworkAssemblies>
    <frameworkAssembly assemblyName="System.Net"  />

    <frameworkAssembly assemblyName="System.ServiceModel" targetFramework="net40" />
</frameworkAssemblies>

包含組件檔Including assembly files

如果遵循建立套件中所述的慣例,即不必在 .nuspec 檔案中明確指定檔案清單。If you follow the conventions described in Creating a Package, you do not have to explicitly specify a list of files in the .nuspec file. nuget pack 命令會自動挑選必要的檔案。The nuget pack command automatically picks up the necessary files.

重要

當套件安裝至專案時,NuGet 會自動將組件參考新增至套件的 DLL,「排除」那些名為 .resources.dll 的參考,因為它們假設是當地語系化的附屬組件。When a package is installed into a project, NuGet automatically adds assembly references to the package's DLLs, excluding those that are named .resources.dll because they are assumed to be localized satellite assemblies. 因此,本該含有基本套件程式碼的檔案請避免使用 .resources.dllFor this reason, avoid using .resources.dll for files that otherwise contain essential package code.

為略過這項自動行為並明確控制套件要包含哪些檔案,請放置 <files> 項目當作 <package> 的子系 (和 <metadata> 的同層級),找出每個有不同 <file> 項目的檔案。To bypass this automatic behavior and explicitly control which files are included in a package, place a <files> element as a child of <package> (and a sibling of <metadata>), identifying each file with a separate <file> element. 例如:For example:

<files>
    <file src="bin\Debug\*.dll" target="lib" />
    <file src="bin\Debug\*.pdb" target="lib" />
    <file src="tools\**\*.*" exclude="**\*.log" />
</files>

使用 NuGet 2.x 及更舊版本,並規劃使用 packages.config;在安裝套件時,也會使用 <files> 項目包含不可變的內容檔。With NuGet 2.x and earlier, and projects using packages.config, the <files> element is also used to include immutable content files when a package is installed. 使用 NuGet 3.3+ 和專案 PackageReference,則改用 <contentFiles> 元素。With NuGet 3.3+ and projects PackageReference, the <contentFiles> element is used instead. 如需詳細資料,請參閱下文中的包含內容檔See Including content files below for details.

檔案項目屬性File element attributes

每個 <file> 項目都會指定下列屬性:Each <file> element specifies the following attributes:

屬性Attribute 描述Description
srcsrc 要包含的檔案位置,會受到 exclude 屬性指定的排除項目約束。The location of the file or files to include, subject to exclusions specified by the exclude attribute. 路徑相對於 .nuspec 檔案,除非指定絕對路徑。The path is relative to the .nuspec file unless an absolute path is specified. 允許萬用字元 *,而雙萬用字元 ** 表示遞迴資料夾搜尋。The wildcard character * is allowed, and the double wildcard ** implies a recursive folder search.
目標target 套件內資料夾的相對路徑是放置原始程式檔的位置,其開頭必須是 libcontentbuildtoolsThe relative path to the folder within the package where the source files are placed, which must begin with lib, content, build, or tools. 請參閱從慣例的工作目錄建立 .nuspecSee Creating a .nuspec from a convention-based working directory.
排除exclude src 位置要排除之以分號分隔的檔案清單或檔案模式。A semicolon-delimited list of files or file patterns to exclude from the src location. 允許萬用字元 *,而雙萬用字元 ** 表示遞迴資料夾搜尋。The wildcard character * is allowed, and the double wildcard ** implies a recursive folder search.

範例Examples

單一組件Single assembly

Source file:
    library.dll

.nuspec entry:
    <file src="library.dll" target="lib" />

Packaged result:
    lib\library.dll

目標 Framework 的特定單一組件Single assembly specific to a target framework

Source file:
    library.dll

.nuspec entry:
    <file src="assemblies\net40\library.dll" target="lib\net40" />

Packaged result:
    lib\net40\library.dll

使用萬用字元的 DLL 集合Set of DLLs using a wildcard

Source files:
    bin\release\libraryA.dll
    bin\release\libraryB.dll

.nuspec entry:
    <file src="bin\release\*.dll" target="lib" />

Packaged result:
    lib\libraryA.dll
    lib\libraryB.dll

不同 Framework 的 DLLDLLs for different frameworks

Source files:
    lib\net40\library.dll
    lib\net20\library.dll

.nuspec entry (using ** recursive search):
    <file src="lib\**" target="lib" />

Packaged result:
    lib\net40\library.dll
    lib\net20\library.dll

排除檔案Excluding files

Source files:
    \tools\fileA.bak
    \tools\fileB.bak
    \tools\fileA.log
    \tools\build\fileB.log

.nuspec entries:
    <file src="tools\*.*" target="tools" exclude="tools\*.bak" />
    <file src="tools\**\*.*" target="tools" exclude="**\*.log" />

Package result:
    (no files)

包含內容檔Including content files

內容檔是不可變的檔案,套件必須將它們包含在專案中。Content files are immutable files that a package needs to include in a project. 因為不可變,所以取用專案不宜修改它們。Being immutable, they are not intended to be modified by the consuming project. 內容檔範例包括:Example content files include:

  • 內嵌為資源的映像Images that are embedded as resources
  • 已編譯原始程式檔Source files that are already compiled
  • 需要以專案的組建輸出包含的指令碼Scripts that need to be included with the build output of the project
  • 套件的組態檔必須包含在專案中,但不需要專門針對任何專案變更Configuration files for the package that need to be included in the project but don't need any project-specific changes

內容檔包含在使用 <files> 項目的套件中,指定 target 屬性中的 content 資料夾。Content files are included in a package using the <files> element, specifying the content folder in the target attribute. 不過,使用 PackageReference 在專案中安裝套件時,會忽略這類檔案,改用 <contentFiles> 元素。However, such files are ignored when the package is installed in a project using PackageReference, which instead uses the <contentFiles> element.

為取得取用專案的最大相容性,套件應該在兩個項目中都指定內容檔。For maximum compatibility with consuming projects, a package ideally specifies the content files in both elements.

內容檔使用 files 項目Using the files element for content files

內容檔只要使用和組件檔相同的格式即可,但要在 target 屬性中指定 content 作為基底資料夾,如下列範例所示。For content files, simply use the same format as for assembly files, but specify content as the base folder in the target attribute as shown in the following examples.

基本內容檔Basic content files

Source files:
    css\mobile\style1.css
    css\mobile\style2.css

.nuspec entry:
    <file src="css\mobile\*.css" target="content\css\mobile" />

Packaged result:
    content\css\mobile\style1.css
    content\css\mobile\style2.css

具有目錄結構的內容檔Content files with directory structure

Source files:
    css\mobile\style.css
    css\mobile\wp7\style.css
    css\browser\style.css

.nuspec entry:
    <file src="css\**\*.css" target="content\css" />

Packaged result:
    content\css\mobile\style.css
    content\css\mobile\wp7\style.css
    content\css\browser\style.css

目標 Framework 的特定內容檔案Content file specific to a target framework

Source file:
    css\cool\style.css

.nuspec entry
    <file src="css\cool\style.css" target="Content" />

Packaged result:
    content\style.css

複製到資料夾,名稱中有點的內容檔Content file copied to a folder with dot in name

在此情況下,NuGet 會看到 target 的副檔名與 src 的副檔名不相符,因此會將 target 名稱的該部分視為資料夾:In this case, NuGet sees that the extension in target does not match the extension in src and thus treats that part of the name in target as a folder:

Source file:
    images\picture.png

.nuspec entry:
    <file src="images\picture.png" target="Content\images\package.icons" />

Packaged result:
    content\images\package.icons\picture.png

無副檔名的內容檔Content files without extensions

若要包含不含副檔名的檔案,請使用 *** 萬用字元:To include files without an extension, use the * or ** wildcards:

Source file:
    flags\installed

.nuspec entry:
    <file src="flags\**" target="flags" />

Packaged result:
    flags\installed

有深路徑和深層目標的內容檔Content files with deep path and deep target

在此情況下,因為原始程式檔的副檔名和目標相符,所以 NuGet 會假設目標是檔案名稱,不是資料夾:In this case, because the file extensions of the source and target match, NuGet assumes that the target is a file name and not a folder:

Source file:
    css\cool\style.css

.nuspec entry:
    <file src="css\cool\style.css" target="Content\css\cool" />
    or:
    <file src="css\cool\style.css" target="Content\css\cool\style.css" />

Packaged result:
    content\css\cool\style.css

重新命名套件中的內容檔Renaming a content file in the package

Source file:
    ie\css\style.css

.nuspec entry:
    <file src="ie\css\style.css" target="Content\css\ie.css" />

Packaged result:
    content\css\ie.css

排除檔案Excluding files

Source file:
    docs\*.txt (multiple files)

.nuspec entry:
    <file src="docs\*.txt" target="content\docs" exclude="docs\admin.txt" />
    or
    <file src="*.txt" target="content\docs" exclude="admin.txt;log.txt" />

Packaged result:
    All .txt files from docs except admin.txt (first example)
    All .txt files from docs except admin.txt and log.txt (second example)

內容檔使用 contentFiles 項目Using the contentFiles element for content files

NuGet 4.0+ 與 PackageReferenceNuGet 4.0+ with PackageReference

根據預設,套件會將內容放在 contentFiles 資料夾 (請參閱下文),而 nuget pack 包含使用預設屬性資料夾中的所有檔案。By default, a package places content in a contentFiles folder (see below) and nuget pack included all files in that folder using default attributes. 在此情況下,.nuspec 完全不需要包含 contentFiles 節點。In this case it's not necessary to include a contentFiles node in the .nuspec at all.

為控制包含哪些檔案,<contentFiles> 項目要指定 <files> 項目的集合,找出正確的檔案。To control which files are included, the <contentFiles> element specifies is a collection of <files> elements that identify the exact files include.

這些檔案是由一組描述如何在專案系統內使用它們的屬性所指定:These files are specified with a set of attributes that describe how they should be used within the project system:

屬性Attribute 描述Description
includeinclude (必要) 要包含的檔案位置,受限於 exclude 屬性所指定的排除項目。(Required) The location of the file or files to include, subject to exclusions specified by the exclude attribute. 除非指定絕對路徑,否則路徑會相對於 contentFiles 資料夾。The path is relative to the contentFiles folder unless an absolute path is specified. 允許萬用字元 *,而雙萬用字元 ** 表示遞迴資料夾搜尋。The wildcard character * is allowed, and the double wildcard ** implies a recursive folder search.
排除exclude src 位置要排除之以分號分隔的檔案清單或檔案模式。A semicolon-delimited list of files or file patterns to exclude from the src location. 允許萬用字元 *,而雙萬用字元 ** 表示遞迴資料夾搜尋。The wildcard character * is allowed, and the double wildcard ** implies a recursive folder search.
buildActionbuildAction 要指派給 MSBuild 內容專案的組建動作,例如 ContentNoneEmbedded ResourceCompile 等等。預設值為 CompileThe build action to assign to the content item for MSBuild, such as Content, None, Embedded Resource, Compile, etc. The default is Compile.
copyToOutputcopyToOutput 布林值,指出是否要將內容專案複製到組建(或發行)輸出檔案夾。A Boolean indicating whether to copy content items to the build (or publish) output folder. 預設為 false。The default is false.
flattenflatten 布林值,指出要將內容項目複製到組建輸出的單一資料夾 (true),或保留套件中的資料夾結構 (false)。A Boolean indicating whether to copy content items to a single folder in the build output (true), or to preserve the folder structure in the package (false). 這個旗標僅適用於將 copyToOutput 旗標設為 true 時。This flag only works when copyToOutput flag is set to true. 預設為 false。The default is false.

安裝套件時,NuGet 會由上而下套用 <contentFiles> 的子項目。When installing a package, NuGet applies the child elements of <contentFiles> from top to bottom. 如有多個項目符合同一檔案,則套用所有項目。If multiple entries match the same file then all entries are applied. 如果相同的屬性發生衝突,則最上層項目會覆寫較低的項目。The top-most entry overrides the lower entries if there is a conflict for the same attribute.

套件資料夾結構Package folder structure

套件專案應該結構化使用下列模式的內容:The package project should structure content using the following pattern:

/contentFiles/{codeLanguage}/{TxM}/{any?}
  • codeLanguages 可能是 csvbfsany,或指定的 $(ProjectLanguage) 小寫對等項codeLanguages may be cs, vb, fs, any, or the lowercase equivalent of a given $(ProjectLanguage)
  • TxM 是 NuGet 支援的任何合法目標 Framework Moniker (請參閱目標 Framework)。TxM is any legal target framework moniker that NuGet supports (see Target frameworks).
  • 這個語法的結尾可以附加任何資料夾結構。Any folder structure may be appended to the end of this syntax.

例如:For example:

Language- and framework-agnostic:
    /contentFiles/any/any/config.xml

net45 content for all languages
    /contentFiles/any/net45/config.xml

C#-specific content for net45 and up
    /contentFiles/cs/net45/sample.cs

空資料夾可以使用 . 選擇不提供特定語言和 TxM 組合的內容,例如:Empty folders can use . to opt out of providing content for certain combinations of language and TxM, for example:

/contentFiles/vb/any/code.vb
/contentFiles/cs/any/.

contentFiles 區段範例Example contentFiles section

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        ...
        <contentFiles>
            <!-- Embed image resources -->
            <files include="any/any/images/dnf.png" buildAction="EmbeddedResource" />
            <files include="any/any/images/ui.png" buildAction="EmbeddedResource" />

            <!-- Embed all image resources under contentFiles/cs/ -->
            <files include="cs/**/*.png" buildAction="EmbeddedResource" />

            <!-- Copy config.xml to the root of the output folder -->
            <files include="cs/uap/config/config.xml" buildAction="None" copyToOutput="true" flatten="true" />

            <!-- Copy run.cmd to the output folder and keep the directory structure -->
            <files include="cs/commands/run.cmd" buildAction="None" copyToOutput="true" flatten="false" />

            <!-- Include everything in the scripts folder except exe files -->
            <files include="cs/net45/scripts/*" exclude="**/*.exe"  buildAction="None" copyToOutput="true" />
        </contentFiles>
        </metadata>
</package>

範例 nuspec 檔案Example nuspec files

簡單的 .nuspec 不指定相依性或檔案A simple .nuspec that does not specify dependencies or files

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>sample</id>
        <version>1.2.3</version>
        <authors>Kim Abercrombie, Franck Halmaert</authors>
        <description>Sample exists only to show a sample .nuspec file.</description>
        <language>en-US</language>
        <projectUrl>http://xunit.codeplex.com/</projectUrl>
        <license type="expression">MIT</license>
    </metadata>
</package>

具有相依性的 .nuspecA .nuspec with dependencies

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>sample</id>
        <version>1.0.0</version>
        <authors>Microsoft</authors>
        <dependencies>
            <dependency id="another-package" version="3.0.0" />
            <dependency id="yet-another-package" version="1.0.0" />
        </dependencies>
    </metadata>
</package>

具有檔案的 .nuspecA .nuspec with files

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>routedebugger</id>
        <version>1.0.0</version>
        <authors>Jay Hamlin</authors>
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <description>Route Debugger is a little utility I wrote...</description>
    </metadata>
    <files>
        <file src="bin\Debug\*.dll" target="lib" />
    </files>
</package>

具有 Framework 組件的 .nuspecA .nuspec with framework assemblies

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>PackageWithGacReferences</id>
        <version>1.0</version>
        <authors>Author here</authors>
        <requireLicenseAcceptance>false</requireLicenseAcceptance>
        <description>
            A package that has framework assemblyReferences depending
            on the target framework.
        </description>
        <frameworkAssemblies>
            <frameworkAssembly assemblyName="System.Web" targetFramework="net40" />
            <frameworkAssembly assemblyName="System.Net" targetFramework="net40-client, net40" />
            <frameworkAssembly assemblyName="Microsoft.Devices.Sensors" targetFramework="sl4-wp" />
            <frameworkAssembly assemblyName="System.Json" targetFramework="sl3" />
        </frameworkAssemblies>
    </metadata>
</package>

在此範例中,特定專案目標會安裝下列項目:In this example, the following are installed for specific project targets:

  • .NET4 -> System.WebSystem.Net.NET4 -> System.Web, System.Net
  • .NET4 Client Profile -> System.Net.NET4 Client Profile -> System.Net
  • Silverlight 3 -> System.JsonSilverlight 3 -> System.Json
  • WindowsPhone -> Microsoft.Devices.SensorsWindowsPhone -> Microsoft.Devices.Sensors