Search code examples
msbuildtypescriptmsbuild-task

Accessing project properties from an external msbuild targets file


I have a common compile.targets file that is used to build many different solutions. In that file I would like to check if any of the contained projects are using TypeScript, and if they are, verify that certain properties are set in those projects (i.e. TypeScriptNoImplicitAny). I currently build the solution like so:

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

What I would like is to be able to create a task that is run for each .csproj in the solution, that has access to all the properties set in the .csproj.

Is this possible? One workaround I tried was using the BeforeTargets attribute along with the targets I know are used to compile 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>

Unfortunately, MSBuild gives me a warning that those TypeScript targets do not exist, and thus check-typescript-options is ignored.


Solution

  • As you say you need to "run" in the context of the individual csproj files. To do this, given your setup I would set one of two properties

    CustomAfterMicrosoftCSharpTargets or CustomAfterMicrosoftCommonTargets

    The easiest way would be to set these like so

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

    In this case you would have $(PathToCustomTargetProj) set to some file path which has targets which run within the csproj pipeline. You could set this to compile.targets and then your check-typescript-options will be called as the BeforeTargets will be evaluated and satisfied correctly.