NuGet 封裝和還原為 MSBuild 目標NuGet pack and restore as MSBuild targets

NuGet 4.0+NuGet 4.0+

使用PackageReference格式時,NuGet 4.0 + 可以直接在專案檔中儲存所有資訊清單中繼資料,而不是使用個別的 .nuspec 檔案。With the PackageReference format, NuGet 4.0+ can store all manifest metadata directly within a project file rather than using a separate .nuspec file.

使用 MSBuild 15.1+,NuGet 也是含 packrestore 目標的第一級 MSBuild 公民,如下所述。With MSBuild 15.1+, NuGet is also a first-class MSBuild citizen with the pack and restore targets as described below. 這些目標可讓您使用 NuGet,就像使用任何其他 MSBuild 工作或目標一樣。These targets allow you to work with NuGet as you would with any other MSBuild task or target. 如需使用 MSBuild 建立 NuGet 套件的指示,請參閱使用 Msbuild 建立 nuget 套件For instructions creating a NuGet package using MSBuild, see Create a NuGet package using MSBuild. (在 NuGet 3.x 和更早版本中,您可以改成透過 NuGet CLI 來使用 packrestore 命令)。(For NuGet 3.x and earlier, you use the pack and restore commands through the NuGet CLI instead.)

目標組建順序Target build order

因為 packrestore 是 MSBuild 目標,所以您可以存取它們,以加強工作流程。Because pack and restore are MSBuild targets, you can access them to enhance your workflow. 例如,假設您想要在封裝套件之後,將套件複製至網路共用。For example, let’s say you want to copy your package to a network share after packing it. 做法是在專案檔中新增下列項目:You can do that by adding the following in your project file:

<Target Name="CopyPackage" AfterTargets="Pack">
  <Copy
    SourceFiles="$(OutputPath)..\$(PackageId).$(PackageVersion).nupkg"
    DestinationFolder="\\myshare\packageshare\"
    />
</Target>

同樣地,您可以撰寫 MSBuild 工作、撰寫您自己的目標,以及在 MSBuild 工作中使用 NuGet 屬性。Similarly, you can write an MSBuild task, write your own target and consume NuGet properties in the MSBuild task.

注意

$(OutputPath) 是相對的,而且預期您是從專案根目錄執行命令。$(OutputPath) is relative and expects that you are running the command from the project root.

封裝目標pack target

對於使用 PackageReference 格式的 .NET Standard 專案,使用 msbuild -t:pack 會從專案檔中繪製輸入,以用來建立 NuGet 套件。For .NET Standard projects using the PackageReference format, using msbuild -t:pack draws inputs from the project file to use in creating a NuGet package.

下表描述可新增至第一個 <PropertyGroup> 節點內之專案檔的 MSBuild 屬性。The table below describes the MSBuild properties that can be added to a project file within the first <PropertyGroup> node. 以滑鼠右鍵按一下專案,然後選取操作功能表上的 [編輯 {project_name}],即可在 Visual Studio 2017 和更新版本中輕鬆地進行這些編輯。You can make these edits easily in Visual Studio 2017 and later by right-clicking the project and selecting Edit {project_name} on the context menu. 為了方便起見,資料表是依 .nuspec 檔案中的對等屬性進行組織。For convenience the table is organized by the equivalent property in a .nuspec file.

請注意,MSBuild 不支援 Owners 中的 Summary.nuspec 屬性。Note that the Owners and Summary properties from .nuspec are not supported with MSBuild.

屬性/NuSpec 值Attribute/NuSpec Value MSBuild 屬性MSBuild Property 預設Default 注意事項Notes
IdId PackageIdPackageId AssemblyNameAssemblyName MSBuild 中的 $(AssemblyName)$(AssemblyName) from MSBuild
版本Version PackageVersionPackageVersion 版本Version 這與 SemVer 相容,例如 “1.0.0”、“1.0.0-beta” 或 “1.0.0-beta-00345”This is semver compatible, for example “1.0.0”, “1.0.0-beta”, or “1.0.0-beta-00345”
VersionPrefixVersionPrefix PackageVersionPrefixPackageVersionPrefix emptyempty 設定 PackageVersion 會覆寫 PackageVersionPrefixSetting PackageVersion overwrites PackageVersionPrefix
VersionSuffixVersionSuffix PackageVersionSuffixPackageVersionSuffix emptyempty MSBuild 中的 $(VersionSuffix)。$(VersionSuffix) from MSBuild. 設定 PackageVersion 會覆寫 PackageVersionSuffixSetting PackageVersion overwrites PackageVersionSuffix
AuthorsAuthors AuthorsAuthors 目前使用者的使用者名稱Username of the current user
擁有者Owners N/AN/A NuSpec 中沒有Not present in NuSpec
標題Title 標題Title PackageIdThe PackageId
描述Description 描述Description "Package Description""Package Description"
著作權Copyright 著作權Copyright emptyempty
RequireLicenseAcceptanceRequireLicenseAcceptance PackageRequireLicenseAcceptancePackageRequireLicenseAcceptance falsefalse
授權license PackageLicenseExpressionPackageLicenseExpression emptyempty 對應至 <license type="expression">Corresponds to <license type="expression">
授權license PackageLicenseFilePackageLicenseFile emptyempty 對應至 <license type="file">Corresponds to <license type="file">. 您必須明確地封裝參考的授權檔案。You need to explicitly pack the referenced license file.
LicenseUrlLicenseUrl PackageLicenseUrlPackageLicenseUrl emptyempty PackageLicenseUrl 已被取代,請使用 PackageLicenseExpression 或 PackageLicenseFile 屬性PackageLicenseUrl is deprecated, use the PackageLicenseExpression or PackageLicenseFile property
ProjectUrlProjectUrl PackageProjectUrlPackageProjectUrl emptyempty
圖示Icon PackageIconPackageIcon emptyempty 您必須明確地封裝參考的圖示影像檔案。You need to explicitly pack the referenced icon image file.
IconUrlIconUrl PackageIconUrlPackageIconUrl emptyempty 為了獲得最佳的下層經驗,除了 PackageIcon之外,也應該指定 PackageIconUrlFor the best downlevel experience, PackageIconUrl should be specified in addition to PackageIcon. 較長的期限,PackageIconUrl 將會被取代。Longer term, PackageIconUrl will be deprecated.
TagsTags PackageTagsPackageTags emptyempty 以分號來分隔標記。Tags are semi-colon delimited.
ReleaseNotesReleaseNotes PackageReleaseNotesPackageReleaseNotes emptyempty
存放庫/UrlRepository/Url RepositoryUrlRepositoryUrl emptyempty 用來複製或取出原始程式碼的存放庫 URL。Repository URL used to clone or retrieve source code. 範例: https://github.com/NuGet/NuGet.Client.gitExample: https://github.com/NuGet/NuGet.Client.git
存放庫/類型Repository/Type RepositoryTypeRepositoryType emptyempty 存放庫類型。Repository type. 範例: gittfsExamples: git, tfs.
存放庫/分支Repository/Branch RepositoryBranchRepositoryBranch emptyempty 選擇性的存放庫分支資訊。Optional repository branch information. 您也必須指定RepositoryUrl ,才能包含這個屬性。RepositoryUrl must also be specified for this property to be included. 範例: master (NuGet 4.7.0 +)Example: master (NuGet 4.7.0+)
存放庫/認可Repository/Commit RepositoryCommitRepositoryCommit emptyempty 選擇性存放庫認可或變更集,用來指出要建立封裝的來源。Optional repository commit or changeset to indicate which source the package was built against. 您也必須指定RepositoryUrl ,才能包含這個屬性。RepositoryUrl must also be specified for this property to be included. 範例: 0e4d1b598f350b3dc675018d539114d1328189ef (NuGet 4.7.0 +)Example: 0e4d1b598f350b3dc675018d539114d1328189ef (NuGet 4.7.0+)
PackageTypePackageType <PackageType>DotNetCliTool, 1.0.0.0;Dependency, 2.0.0.0</PackageType>
摘要Summary 不支援Not supported

封裝目標輸入pack target inputs

  • IsPackableIsPackable
  • SuppressDependenciesWhenPackingSuppressDependenciesWhenPacking
  • PackageVersionPackageVersion
  • PackageIdPackageId
  • AuthorsAuthors
  • 描述Description
  • 著作權Copyright
  • PackageRequireLicenseAcceptancePackageRequireLicenseAcceptance
  • DevelopmentDependencyDevelopmentDependency
  • PackageLicenseExpressionPackageLicenseExpression
  • PackageLicenseFilePackageLicenseFile
  • PackageLicenseUrlPackageLicenseUrl
  • PackageProjectUrlPackageProjectUrl
  • PackageIconUrlPackageIconUrl
  • PackageReleaseNotesPackageReleaseNotes
  • PackageTagsPackageTags
  • PackageOutputPathPackageOutputPath
  • IncludeSymbolsIncludeSymbols
  • IncludeSourceIncludeSource
  • PackageTypesPackageTypes
  • IsToolIsTool
  • RepositoryUrlRepositoryUrl
  • RepositoryTypeRepositoryType
  • RepositoryBranchRepositoryBranch
  • RepositoryCommitRepositoryCommit
  • NoPackageAnalysisNoPackageAnalysis
  • MinClientVersionMinClientVersion
  • IncludeBuildOutputIncludeBuildOutput
  • IncludeContentInPackIncludeContentInPack
  • BuildOutputTargetFolderBuildOutputTargetFolder
  • ContentTargetFoldersContentTargetFolders
  • NuspecFileNuspecFile
  • NuspecBasePathNuspecBasePath
  • NuspecPropertiesNuspecProperties

封裝案例pack scenarios

隱藏相依性Suppress dependencies

若要從產生的 NuGet 套件中抑制套件相依性,請將 SuppressDependenciesWhenPacking 設定為 true,這會允許從產生的 nupkg 檔略過所有相依性。To suppress package dependencies from generated NuGet package, set SuppressDependenciesWhenPacking to true which will allow skipping all the dependencies from generated nupkg file.

PackageIconUrlPackageIconUrl

PackageIconUrl 將會取代為新的PackageIcon屬性。PackageIconUrl will be deprecated in favor of the new PackageIcon property.

從 NuGet 5.3 & Visual Studio 2019 16.3 版開始,如果套件中繼資料只指定 PackageIconUrlpack 會引發NU5048警告。Starting with NuGet 5.3 & Visual Studio 2019 version 16.3, pack will raise NU5048 warning if the package metadata only specifies PackageIconUrl.

PackageIconPackageIcon

提示

您應該同時指定 PackageIconPackageIconUrl,以維持與尚未支援 PackageIcon的用戶端和來源的回溯相容性。You should specify both PackageIcon and PackageIconUrl to maintain backward compatibility with clients and sources that do not yet support PackageIcon. Visual Studio 將支援未來版本中來自以資料夾為基礎的來源之套件的 PackageIconVisual Studio will support PackageIcon for packages coming from a folder-based source in a future release.

封裝圖示影像檔案Packing an icon image file

封裝圖示影像檔時,您必須使用 PackageIcon 屬性來指定相對於封裝根目錄的封裝路徑。When packing an icon image file, you need to use PackageIcon property to specify the package path, relative to the root of the package. 此外,您必須確定檔案已包含在封裝中。In addition, you need to make sure that the file is included in the package. 影像檔案大小限制為 1 MB。Image file size is limited to 1 MB. 支援的檔案格式包括 JPEG 和 PNG。Supported file formats include JPEG and PNG. 我們建議使用128x128 的映射解析度。We recommend an image resolution of 128x128.

例如,For example:

<PropertyGroup>
    ...
    <PackageIcon>icon.png</PackageIcon>
    ...
</PropertyGroup>

<ItemGroup>
    ...
    <None Include="images\icon.png" Pack="true" PackagePath="\"/>
    ...
</ItemGroup>

封裝圖示範例Package Icon sample.

如需對等的 nuspec,請參閱圖示的 nuspec 參考For the nuspec equivalent, take a look at nuspec reference for icon.

輸出組件Output assemblies

nuget pack 會複製副檔名為 .exe.dll.xml.winmd.json.pri 的輸出檔案。nuget pack copies output files with extensions .exe, .dll, .xml, .winmd, .json, and .pri. 所複製的輸出檔案取決於 MSBuild 從 BuiltOutputProjectGroup 目標所提供的項目。The output files that are copied depend on what MSBuild provides from the BuiltOutputProjectGroup target.

在專案檔或命令列中,您可以使用兩種 MSBuild 屬性來控制放置輸出組件的位置:There are two MSBuild properties that you can use in your project file or command line to control where output assemblies go:

  • IncludeBuildOutput:布林值,決定是否應該在套件中包含組建輸出組件。IncludeBuildOutput: A boolean that determines whether the build output assemblies should be included in the package.
  • BuildOutputTargetFolder:指定應該在其中放置輸出組件的資料夾。BuildOutputTargetFolder: Specifies the folder in which the output assemblies should be placed. 輸出組件 (及其他輸出檔) 會複製到其相關的架構資料夾中。The output assemblies (and other output files) are copied into their respective framework folders.

套件參考Package references

請參閱專案檔中的套件參考See Package References in Project Files.

專案對專案參考Project to project references

預設會將專案對專案參考視為 NuGet 套件參考,例如:Project to project references are considered by default as nuget package references, for example:

<ProjectReference Include="..\UwpLibrary2\UwpLibrary2.csproj"/>

您也可以將下列中繼資料新增至您的專案參考:You can also add the following metadata to your project reference:

<IncludeAssets>
<ExcludeAssets>
<PrivateAssets>

在套件內包含內容Including content in a package

若要包含內容,請將額外的中繼資料新增至現有的 <Content> 項目。To include content, add extra metadata to the existing <Content> item. 除非您覆寫為下列這類項目,否則 "Content" 類型的所有項目預設都會包含在套件中:By default everything of type "Content" gets included in the package unless you override with entries like the following:

<Content Include="..\win7-x64\libuv.txt">
 <Pack>false</Pack>
</Content>

除非您指定套件路徑,否則所有項目預設都會新增至套件內的 contentcontentFiles\any\<target_framework> 資料夾根目錄,並保留相對資料夾結構:By default, everything gets added to the root of the content and contentFiles\any\<target_framework> folder within a package and preserves the relative folder structure, unless you specify a package path:

<Content Include="..\win7-x64\libuv.txt">
  <Pack>true</Pack>
  <PackagePath>content\myfiles\</PackagePath>
</Content>

如果您想要將所有內容都只複製至特定根資料夾 (而不是 contentcontentFiles),則可以使用 MSBuild 屬性 ContentTargetFolders,其預設為 "content;contentFiles",但可以設定為任何其他資料夾名稱。If you want to copy all your content to only a specific root folder(s) (instead of content and contentFiles both), you can use the MSBuild property ContentTargetFolders, which defaults to "content;contentFiles" but can be set to any other folder names. 請注意,根據 ContentTargetFolders,只在 contentFiles\any\<target_framework> 中指定 "contentFiles" 會將檔案放在 contentFiles\<language>\<target_framework>buildAction 下方。Note that just specifying "contentFiles" in ContentTargetFolders puts files under contentFiles\any\<target_framework> or contentFiles\<language>\<target_framework> based on buildAction.

PackagePath 可以是以分號分隔的一組目標路徑。PackagePath can be a semicolon-delimited set of target paths. 指定空的套件路徑會將檔案新增至套件的根目錄。Specifying an empty package path would add the file to the root of the package. 例如,下列會將 libuv.txt 新增至 content\myfilescontent\samples 和套件根目錄:For example, the following adds libuv.txt to content\myfiles, content\samples, and the package root:

<Content Include="..\win7-x64\libuv.txt">
  <Pack>true</Pack>
  <PackagePath>content\myfiles;content\sample;;</PackagePath>
</Content>

另有 MSBuild 屬性 $(IncludeContentInPack) 預設為 trueThere is also an MSBuild property $(IncludeContentInPack), which defaults to true. 如果這在任何專案上設定為 false,則 NuGet 套件不會包含該專案的內容。If this is set to false on any project, then the content from that project are not included in the nuget package.

您可在上述任何項目上設定的其他封裝特定中繼資料包含 <PackageCopyToOutput><PackageFlatten>,其在輸出 nuspec 的 CopyToOutput 項目上設定 FlattencontentFiles 值。Other pack specific metadata that you can set on any of the above items includes <PackageCopyToOutput> and <PackageFlatten> which sets CopyToOutput and Flatten values on the contentFiles entry in the output nuspec.

注意

除了 Content 項目之外,還可以在建置動作為 Compile、EmbeddedResource、ApplicationDefinition、Page、Resource、SplashScreen、DesignData、DesignDataWithDesignTimeCreateableTypes、CodeAnalysisDictionary、AndroidAsset、AndroidResource、BundleResource 或 None 的檔案上設定 <Pack><PackagePath> 中繼資料。Apart from Content items, the <Pack> and <PackagePath> metadata can also be set on files with a build action of Compile, EmbeddedResource, ApplicationDefinition, Page, Resource, SplashScreen, DesignData, DesignDataWithDesignTimeCreateableTypes, CodeAnalysisDictionary, AndroidAsset, AndroidResource, BundleResource or None.

針對封裝,若要在使用萬用字元模式時將檔案名稱附加至套件路徑,您套件路徑的結尾必須是資料夾分隔符號字元,否則會將套件路徑視為包含檔案名稱的完整路徑。For pack to append the filename to your package path when using globbing patterns, your package path must end with the folder separator character, otherwise the package path is treated as the full path including the file name.

IncludeSymbolsIncludeSymbols

使用 MSBuild -t:pack -p:IncludeSymbols=true 時,會複製對應的 .pdb 檔案與其他輸出檔案 (.dll.exe.winmd.xml.json.pri)。When using MSBuild -t:pack -p:IncludeSymbols=true, the corresponding .pdb files are copied along with other output files (.dll, .exe, .winmd, .xml, .json, .pri). 請注意,設定 IncludeSymbols=true 時會建立一般套件「和」符號套件。Note that setting IncludeSymbols=true creates a regular package and a symbols package.

IncludeSourceIncludeSource

這與 IncludeSymbols 相同,差異在於它也會複製原始程式檔和 .pdb 檔案。This is the same as IncludeSymbols, except that it copies source files along with .pdb files as well. 所有 Compile 類型的檔案都會覆寫 src\<ProjectName>\,並保留所產生套件中的相對路徑資料夾結構。All files of type Compile are copied over to src\<ProjectName>\ preserving the relative path folder structure in the resulting package. 這也適用於任何 ProjectReference 的原始程式檔,而這些原始程式檔將 TreatAsPackageReference 設定為 falseThe same also happens for source files of any ProjectReference which has TreatAsPackageReference set to false.

若類型為 Compile 的檔案位於專案資料夾之外,就只會將其新增至 src\<ProjectName>\If a file of type Compile, is outside the project folder, then it's just added to src\<ProjectName>\.

封裝授權運算式或授權檔案Packing a license expression or a license file

使用授權運算式時,應該使用 PackageLicenseExpression 屬性。When using a license expression, the PackageLicenseExpression property should be used. 授權運算式範例License expression sample.

<PropertyGroup>
    <PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>

深入瞭解 NuGet.org 所接受的授權運算式和授權。Learn more about license expressions and licenses that are accepted by NuGet.org.

封裝授權檔案時,您必須使用 PackageLicenseFile 屬性來指定相對於封裝根目錄的封裝路徑。When packing a license file, you need to use PackageLicenseFile property to specify the package path, relative to the root of the package. 此外,您必須確定檔案已包含在封裝中。In addition, you need to make sure that the file is included in the package. 例如,For example:

<PropertyGroup>
    <PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
</PropertyGroup>

<ItemGroup>
    <None Include="licenses\LICENSE.txt" Pack="true" PackagePath=""/>
</ItemGroup>

授權檔案範例License file sample.

IsToolIsTool

使用 MSBuild -t:pack -p:IsTool=true 時,會將輸出組件案例中所指定的所有輸出檔案都複製至 tools 資料夾,而非 lib 資料夾。When using MSBuild -t:pack -p:IsTool=true, all output files, as specified in the Output Assemblies scenario, are copied to the tools folder instead of the lib folder. 請注意,這與 DotNetCliTool 不同,該項目是在 PackageType 檔案中設定 .csproj 所指定。Note that this is different from a DotNetCliTool which is specified by setting the PackageType in .csproj file.

使用 .nuspec 封裝Packing using a .nuspec

雖然建議您改為在專案檔中包含通常在 .nuspec 檔案中的所有屬性,但您可以選擇使用 .nuspec 檔案來封裝專案。Although it is recommended that you include all the properties that are usually in the .nuspec file in the project file instead, you can choose to use a .nuspec file to pack your project. 若為使用 PackageReference的非 SDK 樣式專案,您必須匯入 NuGet.Build.Tasks.Pack.targets,才能執行封裝工作。For a non-SDK-style project that uses PackageReference, you must import NuGet.Build.Tasks.Pack.targets so that the pack task can be executed. 您仍然需要還原專案,才能封裝 nuspec 檔案。You still need to restore the project before you can pack a nuspec file. (根據預設,SDK 樣式專案包含套件目標)。(An SDK-style project includes the pack targets by default.)

專案檔的目標 framework 不相關,也不會在封裝 nuspec 時使用。The target framework of the project file is irrelevant and not used when packing a nuspec. 下列三個 MSBuild 屬性與使用 .nuspec 進行封裝有關:The following three MSBuild properties are relevant to packing using a .nuspec:

  1. NuspecFile:將用於封裝之 .nuspec 檔案的相對或絕對路徑。NuspecFile: relative or absolute path to the .nuspec file being used for packing.
  2. NuspecProperties:以分號分隔的索引鍵=值組清單。NuspecProperties: a semicolon-separated list of key=value pairs. 基於 MSBuild 命令列剖析的運作方式,必須如下指定多個屬性:-p:NuspecProperties=\"key1=value1;key2=value2\"Due to the way MSBuild command-line parsing works, multiple properties must be specified as follows: -p:NuspecProperties=\"key1=value1;key2=value2\".
  3. NuspecBasePath.nuspec 檔案的基底路徑。NuspecBasePath: Base path for the .nuspec file.

如果使用 dotnet.exe 來封裝您的專案,則請使用下列這類命令:If using dotnet.exe to pack your project, use a command like the following:

dotnet pack <path to .csproj file> -p:NuspecFile=<path to nuspec file> -p:NuspecProperties=<> -p:NuspecBasePath=<Base path> 

如果使用 MSBuild 來封裝您的專案,則請使用下列這類命令:If using MSBuild to pack your project, use a command like the following:

msbuild -t:pack <path to .csproj file> -p:NuspecFile=<path to nuspec file> -p:NuspecProperties=<> -p:NuspecBasePath=<Base path> 

請注意,使用 dotnet 封裝 nuspec 或 msbuild 也會導致預設建立專案。Please note that packing a nuspec using dotnet.exe or msbuild also leads to building the project by default. --no-build 屬性傳遞給 dotnet,這相當於在專案檔中設定 <NoBuild>true</NoBuild>,並在專案檔中設定 <IncludeBuildOutput>false</IncludeBuildOutput>,可以避免這種情況。This can be avoided by passing --no-build property to dotnet.exe, which is the equivalent of setting <NoBuild>true</NoBuild> in your project file, along with setting <IncludeBuildOutput>false</IncludeBuildOutput> in the project file.

封裝 nuspec 檔案的 .csproj檔案範例如下:An example of a .csproj file to pack a nuspec file is:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <NoBuild>true</NoBuild>
    <IncludeBuildOutput>false</IncludeBuildOutput>
    <NuspecFile>PATH_TO_NUSPEC_FILE</NuspecFile>
    <NuspecProperties>add nuspec properties here</NuspecProperties>
    <NuspecBasePath>optional to provide</NuspecBasePath>
  </PropertyGroup>
</Project>

用來建立自訂套件的先進擴充功能點Advanced extension points to create customized package

pack 目標提供兩個擴充點,可在內部、目標 framework 特定組建中執行。The pack target provides two extension points that run in the inner, target framework specific build. 擴充點支援將目標 framework 特定的內容和元件包含在封裝中:The extension points support including target framework specific content and assemblies into a package:

  • TargetsForTfmSpecificBuildOutput 目標:用於 lib 資料夾內的檔案,或使用 BuildOutputTargetFolder指定的資料夾。TargetsForTfmSpecificBuildOutput target: Use for files inside the lib folder or a folder specified using BuildOutputTargetFolder.
  • TargetsForTfmSpecificContentInPackage 目標:用於 BuildOutputTargetFolder以外的檔案。TargetsForTfmSpecificContentInPackage target: Use for files outside the BuildOutputTargetFolder.

TargetsForTfmSpecificBuildOutputTargetsForTfmSpecificBuildOutput

撰寫自訂目標,並將它指定為 $(TargetsForTfmSpecificBuildOutput) 屬性的值。Write a custom target and specify it as the value of the $(TargetsForTfmSpecificBuildOutput) property. 對於需要移入 BuildOutputTargetFolder 的任何檔案(預設為 lib),目標應該將這些檔案寫入 ItemGroup BuildOutputInPackage,並設定下列兩個中繼資料值:For any files that need to go into the BuildOutputTargetFolder (lib by default), the target should write those files into the ItemGroup BuildOutputInPackage and set the following two metadata values:

  • FinalOutputPath:檔案的絕對路徑;如果未提供,則會使用身分識別來評估來源路徑。FinalOutputPath: The absolute path of the file; if not provided, the Identity is used to evaluate source path.
  • TargetPath:(選擇性)當檔案需要移至 lib\<TargetFramework> 內的子資料夾(例如,其各自的文化特性資料夾下的附屬元件)時設定。TargetPath: (Optional) Set when the file needs to go into a subfolder within lib\<TargetFramework> , like satellite assemblies that go under their respective culture folders. 預設為檔案名。Defaults to the name of the file.

範例:Example:

<PropertyGroup>
  <TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);GetMyPackageFiles</TargetsForTfmSpecificBuildOutput>
</PropertyGroup>

<Target Name="GetMyPackageFiles">
  <ItemGroup>
    <BuildOutputInPackage Include="$(OutputPath)cs\$(AssemblyName).resources.dll">
        <TargetPath>cs</TargetPath>
    </BuildOutputInPackage>
  </ItemGroup>
</Target>

TargetsForTfmSpecificContentInPackageTargetsForTfmSpecificContentInPackage

撰寫自訂目標,並將它指定為 $(TargetsForTfmSpecificContentInPackage) 屬性的值。Write a custom target and specify it as the value of the $(TargetsForTfmSpecificContentInPackage) property. 針對要包含在封裝中的任何檔案,目標應該將這些檔案寫入 ItemGroup TfmSpecificPackageFile 並設定下列選擇性中繼資料:For any files to include in the package, the target should write those files into the ItemGroup TfmSpecificPackageFile and set the following optional metadata:

  • PackagePath:在封裝中應該輸出檔案的路徑。PackagePath: Path where the file should be output in the package. 如果將多個檔案新增至相同的封裝路徑,NuGet 就會發出警告。NuGet issues a warning if more than one file is added to the same package path.
  • BuildAction:要指派給檔案的組建動作,只有在封裝路徑位於 contentFiles 資料夾中時才需要。BuildAction: The build action to assign to the file, required only if the package path is in the contentFiles folder. 預設值為 "None"。Defaults to "None".

範例:An example:

<PropertyGroup>
  <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);CustomContentTarget</TargetsForTfmSpecificContentInPackage>
</PropertyGroup>

<Target Name="CustomContentTarget">
  <ItemGroup>
    <TfmSpecificPackageFile Include="abc.txt">
      <PackagePath>mycontent/$(TargetFramework)</PackagePath>
    </TfmSpecificPackageFile>
    <TfmSpecificPackageFile Include="Extensions/ext.txt" Condition="'$(TargetFramework)' == 'net46'">
      <PackagePath>net46content</PackagePath>
    </TfmSpecificPackageFile>  
  </ItemGroup>
</Target>  

還原目標restore target

MSBuild -t:restore (nuget restoredotnet restore 與 .NET Core 專案搭配使用) 會還原專案檔中所參考的套件,如下所示:MSBuild -t:restore (which nuget restore and dotnet restore use with .NET Core projects), restores packages referenced in the project file as follows:

  1. 讀取所有專案對專案參考Read all project to project references
  2. 讀取專案屬性來尋找中繼資料夾和目標架構Read the project properties to find the intermediate folder and target frameworks
  3. 將 MSBuild 資料傳遞至 Nuget.exe。 .dllPass MSBuild data to NuGet.Build.Tasks.dll
  4. 執行還原Run restore
  5. 下載套件Download packages
  6. 撰寫資產檔案、目標和屬性Write assets file, targets, and props

restore 目標適用于使用 PackageReference 格式的專案。The restore target works only for projects using the PackageReference format. 它不適用於使用 packages.config 格式的專案;請改用nuget 還原It does not work for projects using the packages.config format; use nuget restore instead.

還原屬性Restore properties

其他還原設定可能來自專案檔中的 MSBuild 屬性。Additional restore settings may come from MSBuild properties in the project file. 您也可以從命令列,使用 -p: 參數設定值 (請參閱下列<範例>)。Values can also be set from the command line using the -p: switch (see Examples below).

屬性Property 描述Description
RestoreSourcesRestoreSources 以分號分隔的套件來源清單。Semicolon-delimited list of package sources.
RestorePackagesPathRestorePackagesPath 使用者套件資料夾路徑。User packages folder path.
RestoreDisableParallelRestoreDisableParallel 限制逐一進行下載。Limit downloads to one at a time.
RestoreConfigFileRestoreConfigFile 要套用之 Nuget.Config 檔案的路徑。Path to a Nuget.Config file to apply.
RestoreNoCacheRestoreNoCache 若為 true,則避免使用快取的封裝。If true, avoids using cached packages. 請參閱管理全域套件和快取資料夾。See Managing the global packages and cache folders.
RestoreIgnoreFailedSourcesRestoreIgnoreFailedSources 如果為 true,請忽略失敗或遺漏的套件來源。If true, ignores failing or missing package sources.
RestoreFallbackFoldersRestoreFallbackFolders 回溯資料夾,其使用方式與使用者套件資料夾相同。Fallback folders, used in the same way the user packages folder is used.
RestoreAdditionalProjectSourcesRestoreAdditionalProjectSources 還原期間要使用的其他來源。Additional sources to use during restore.
RestoreAdditionalProjectFallbackFoldersRestoreAdditionalProjectFallbackFolders 還原期間要使用的其他 fallback 資料夾。Additional fallback folders to use during restore.
RestoreAdditionalProjectFallbackFoldersExcludesRestoreAdditionalProjectFallbackFoldersExcludes 排除在 RestoreAdditionalProjectFallbackFolders 中指定的 fallback 資料夾Excludes fallback folders specified in RestoreAdditionalProjectFallbackFolders
RestoreTaskAssemblyFileRestoreTaskAssemblyFile NuGet.Build.Tasks.dll 的路徑。Path to NuGet.Build.Tasks.dll.
RestoreGraphProjectInputRestoreGraphProjectInput 要還原的專案清單 (以分號分隔),其中應包含絕對路徑。Semicolon-delimited list of projects to restore, which should contain absolute paths.
RestoreUseSkipNonexistentTargetsRestoreUseSkipNonexistentTargets 透過 MSBuild 收集項目時,它會決定是否要使用 SkipNonexistentTargets 優化進行收集。When the projects are collected via MSBuild it determines whether they are collected using the SkipNonexistentTargets optimization. [未設定] 時,預設為 trueWhen not set, defaults to true. 當無法匯入專案的目標時,結果會是失敗快速的行為。The consequence is a fail-fast behavior when a project's targets cannot be imported.
MSBuildProjectExtensionsPathMSBuildProjectExtensionsPath 輸出檔案夾,預設為 BaseIntermediateOutputPathobj 資料夾。Output folder, defaulting to BaseIntermediateOutputPath and the obj folder.
RestoreForceRestoreForce 在以 PackageReference 為基礎的專案中,即使上次還原成功,也會強制解析所有相依性。In PackageReference based projects, forces all dependencies to be resolved even if the last restore was successful. 指定此旗標類似于刪除 project.assets.json 檔案。Specifying this flag is similar to deleting the project.assets.json file. 這不會略過 HTTP 快取。This does not bypass the http-cache.
RestorePackagesWithLockFileRestorePackagesWithLockFile 選擇使用鎖定檔案。Opts into the usage of a lock file.
RestoreLockedModeRestoreLockedMode 以鎖定模式執行還原。Run restore in locked mode. 這表示還原將不會重新評估相依性。This means that restore will not reevaluate the dependencies.
NuGetLockFilePathNuGetLockFilePath 鎖定檔案的自訂位置。A custom location for the lock file. 預設位置是專案的旁邊,而且名為 packages.lock.jsonThe default location is next to the project and is named packages.lock.json.
RestoreForceEvaluateRestoreForceEvaluate 強制還原以重新計算相依性並更新鎖定檔案,而不會出現任何警告。Forces restore to recompute the dependencies and update the lock file without any warning.

範例Examples

命令列:Command line:

msbuild -t:restore -p:RestoreConfigFile=<path>

專案檔:Project file:

<PropertyGroup>
    <RestoreIgnoreFailedSource>true</RestoreIgnoreFailedSource>
</PropertyGroup>

Restore outputsRestore outputs

還原會在組建 obj 資料夾中建立下列檔案:Restore creates the following files in the build obj folder:

檔案File 描述Description
project.assets.json 包含所有封裝參考的相依性圖形。Contains the dependency graph of all package references.
{projectName}.projectFileExtension.nuget.g.props 套件中所含 MSBuild 屬性的參考References to MSBuild props contained in packages
{projectName}.projectFileExtension.nuget.g.targets 套件中所含 MSBuild 目標的參考References to MSBuild targets contained in packages

使用一個 MSBuild 命令還原和建立Restoring and building with one MSBuild command

因為 NuGet 可以還原會導致 MSBuild 目標和 .props 的封裝,所以還原和組建評估會以不同的全域屬性執行。Due to the fact that NuGet can restore packages that bring down MSBuild targets and props, the restore and build evaluations are run with different global properties. 這表示下列程式將會有無法預測且通常不正確的行為。This means that the following will have an unpredictable and often incorrect behavior.

msbuild -t:restore,build

相反地,建議的方法是:Instead the recommended approach is:

msbuild -t:build -restore

相同的邏輯也適用于類似 build的其他目標。The same logic applies to other targets similar to build.

PackageTargetFallbackPackageTargetFallback

PackageTargetFallback 項目可讓您指定一組要在還原套件時使用的相容目標。The PackageTargetFallback element allows you to specify a set of compatible targets to be used when restoring packages. 其設計目的是要讓使用 dotnet TxM 的套件可以與未宣告 dotnet TxM 的相容套件一起運作。It's designed to allow packages that use a dotnet TxM to work with compatible packages that don't declare a dotnet TxM. 也就是說,如果您的專案使用 dotnet TxM,除非您將 <PackageTargetFallback> 新增至專案,以讓非 dotnet 平台變成與 dotnet 相容,否則其相依的所有套件也必須要有 dotnet TxM。That is, if your project uses the dotnet TxM, then all the packages it depends on must also have a dotnet TxM, unless you add the <PackageTargetFallback> to your project in order to allow non-dotnet platforms to be compatible with dotnet.

例如,如果專案使用 netstandard1.6 TxM,而且相依套件僅包含 lib/net45/a.dlllib/portable-net45+win81/a.dll,則無法建置專案。For example, if the project is using the netstandard1.6 TxM, and a dependent package contains only lib/net45/a.dll and lib/portable-net45+win81/a.dll, then the project will fail to build. 如果您想要匯入的是第二個 DLL,則可以如下新增 PackageTargetFallback,指出 portable-net45+win81 DLL 相容:If what you want to bring in is the latter DLL, then you can add a PackageTargetFallback as follows to say that the portable-net45+win81 DLL is compatible:

<PackageTargetFallback Condition="'$(TargetFramework)'=='netstandard1.6'">
    portable-net45+win81
</PackageTargetFallback>

若要宣告專案中所有目標的後援,請省略 Condition 屬性。To declare a fallback for all targets in your project, leave off the Condition attribute. 您也可以包含 PackageTargetFallback 來擴充任何現有 $(PackageTargetFallback),如下所示:You can also extend any existing PackageTargetFallback by including $(PackageTargetFallback) as shown here:

<PackageTargetFallback>
    $(PackageTargetFallback);portable-net45+win81
</PackageTargetFallback >

取代還原圖形中的一個程式庫Replacing one library from a restore graph

如果還原內含錯誤的組件,您可以排除該套件預設選項,並將其取代為您自己的選項。If a restore is bringing the wrong assembly, it's possible to exclude that packages default choice, and replace it with your own choice. 首先,會有最上層 PackageReference,但排除所有資產:First with a top level PackageReference, exclude all assets:

<PackageReference Include="Newtonsoft.Json" Version="9.0.1">
  <ExcludeAssets>All</ExcludeAssets>
</PackageReference>

接下來,新增您自己對 DLL 之適當本機複本的參考:Next, add your own reference to the appropriate local copy of the DLL:

<Reference Include="Newtonsoft.Json.dll" />