从外部 msbuild 目标文件访问项目属性

Accessing project properties from an external msbuild targets file

我有一个通用的 compile.targets 文件,用于构建许多不同的解决方案。在该文件中,我想检查是否有任何包含的项目正在使用 TypeScript,如果是,请验证是否在这些项目中设置了某些属性(即 TypeScriptNoImplicitAny)。我目前这样构建解决方案:

  <Target Name="my-compile-target">
    <MSBuild Projects="%(SolutionFile.FullPath)"/>
  </Target>

我想要的是能够为解决方案中的每个 .csproj 创建一个 运行 的任务,该任务可以访问 .csproj 中设置的所有属性.

这可能吗?我 尝试 的一种解决方法是使用 BeforeTargets 属性以及我知道用于编译 TypeScript 的目标:

<Target Name="check-typescript-options" BeforeTargets="CompileTypeScript;CompileTypeScriptWithTSConfig">
    <Message Condition="'$(TypeScriptToolsVersion)' != ''" Text="Tools Version is $(TypeScriptToolsVersion)"></Message>
    <Message Condition="'$(TypeScriptToolsVersion)' == ''" Text="No tools version found"></Message>
</Target>

不幸的是,MSBuild 警告我这些 TypeScript 目标不存在,因此 check-typescript-options 被忽略了。

如您所说,您需要 "run" 在各个 csproj 文件的上下文中。为此,根据您的设置,我将设置两个属性之一

CustomAfterMicrosoftCSharpTargetsCustomAfterMicrosoftCommonTargets

最简单的方法是像这样设置这些

<Target Name="my-compile-target">
    <MSBuild Projects="%(SolutionFile.FullPath)"
             Properties="CustomAfterMicrosoftCSharpTargets=$(PathToCustomTargetProj);"  />
</Target>

在这种情况下,您可以将 $(PathToCustomTargetProj) 设置为某个文件路径,该路径的目标在 csproj 管道中 运行。您可以将其设置为 compile.targets 然后您的 check-typescript-options 将被称为 BeforeTargets 将被正确评估和满足。