Share via


自訂方案組建

MSBuild 在建置方案檔時,會先在內部將其轉換成專案檔,再建置該檔案。 產生的專案檔會在定義任何目標之前匯入 before.{solutionname}.sln.targets,並在匯入目標之後匯入 after.{solutionname}.sln.targets,包括安裝到 $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportBefore$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ImportAfter 目錄的目標。

例如,您可以在建置 MyCustomizedSolution.sln 之後,定義新的目標來寫入自訂記錄訊息,方法是在名為 after.MyCustomizedSolution.sln.targets 的相同目錄中建立一個檔案,其中包含:

<Project>
 <Target Name="EmitCustomMessage" AfterTargets="Build">
   <Message Importance="High" Text="The solution has completed the Build target" />
 </Target>
</Project>

方案組建與專案組建不同,因此這裡的設定不會影響專案組建。

重要

以這種方式自訂方案組建只適用於使用 MSBuild.exe 的命令列建置。 它適用於 Visual Studio 內的組建。 基於這個理由,不建議將自訂放在解決方案層級。 自訂解決方案中所有專案的較佳替代方案是使用 Directory.Build.propsDirectory.build.targets 方案資料夾中的檔案,如本文其他地方所述。

當您有許多想要以相同方式擴充的解決方案檔案時,但不想寫入 $(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\SolutionFile\ 資料夾 (這通常需要更高的權限),您可以建立 Directory.Solution.propsDirectory.Solution.targets 的檔案,並將其放在您想要擴充之方案檔上方的根路徑中。 Directory.Solution.props 會在方案組建的開頭匯入,而 Directory.Solution.targets 會在方案組建的結尾匯入。 當您建置方案檔時,Directory.Build.propsDirectory.Build.targets 不會匯入,因此您必須改用 Directory.Solution.propsDirectory.Solution.targets。 它們不會隱含地匯入彼此。

當您在根資料夾中 Directory.Solution.propsDirectory.Solution.targets,但在該資料夾下有不想匯入它們的解決方案時,您可以使用先前 before.{solutionname}.sln.targetsafter.{solutionname}.sln.targets 所述的解決方案特定檔案,並將屬性 $(ImportDirectorySolutionProps)$(ImportDirectorySolutionTargets) 設定為 false。 或者,您可以使用屬性 $(DirectorySolutionPropsPath)$(DirectorySolutionTargetsPath) 來指定這些檔案的不同位置。 如果您有各種解決方案子集需要特定屬性值或子集通用的目標,這會很有幫助。